GLM Part6

Author

Murray Logan

Published

30/07/2023

1 Preparations

Load the necessary libraries

library(tidyverse)  #for data wrangling etc
library(rstanarm)   #for fitting models in STAN
library(cmdstanr)   #for cmdstan
library(brms)       #for fitting models in STAN
library(standist)   #for exploring distributions
library(HDInterval) #for HPD intervals
library(posterior)  #for posterior draws
library(coda)       #for diagnostics
library(bayesplot)  #for diagnostics
library(ggmcmc)     #for diagnostics
library(rstan)      #for interfacing with STAN
library(DHARMa)     #for residual diagnostics
library(emmeans)    #for marginal means etc
library(broom)      #for tidying outputs
library(broom.mixed) #for tidying MCMC outputs
library(tidybayes)  #for more tidying outputs
library(ggeffects)  #for partial plots
library(patchwork)  #for multiple figures
library(bayestestR) #for ROPE
library(see)        #for some plots
library(ggridges)   #for ridge plots
library(easystats)     #framework for stats, modelling and visualisation
source('helperFunctions.R')

2 Scenario

An ecologist studying a rocky shore at Phillip Island, in southeastern Australia, was interested in how clumps of intertidal mussels are maintained (Quinn 1988). In particular, he wanted to know how densities of adult mussels affected recruitment of young individuals from the plankton. As with most marine invertebrates, recruitment is highly patchy in time, so he expected to find seasonal variation, and the interaction between season and density - whether effects of adult mussel density vary across seasons - was the aspect of most interest.

The data were collected from four seasons, and with two densities of adult mussels. The experiment consisted of clumps of adult mussels attached to the rocks. These clumps were then brought back to the laboratory, and the number of baby mussels recorded. There were 3-6 replicate clumps for each density and season combination.

Table 1: Format of the quinn.csv data file
SEASON DENSITY RECRUITS SQRTRECRUITS GROUP
Spring Low 15 3.87 SpringLow
.. .. .. .. ..
Spring High 11 3.32 SpringHigh
.. .. .. .. ..
Summer Low 21 4.58 SummerLow
.. .. .. .. ..
Summer High 34 5.83 SummerHigh
.. .. .. .. ..
Autumn Low 14 3.74 AutumnLow
.. .. .. .. ..
Table 2: Description of the variables in the quinn data file
SEASON Categorical listing of Season in which mussel clumps were collected ­ independent variable
DENSITY Categorical listing of the density of mussels within mussel clump ­ independent variable
RECRUITS The number of mussel recruits ­ response variable
SQRTRECRUITS Square root transformation of RECRUITS - needed to meet the test assumptions
GROUPS Categorical listing of Season/Density combinations - used for checking ANOVA assumptions

Figure 1: Mussel

3 Read in the data

quinn <- read_csv("../public/data/quinn.csv", trim_ws = TRUE)
Rows: 42 Columns: 5
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (3): SEASON, DENSITY, GROUP
dbl (2): RECRUITS, SQRTRECRUITS

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
glimpse(quinn)
Rows: 42
Columns: 5
$ SEASON       <chr> "Spring", "Spring", "Spring", "Spring", "Spring", "Spring…
$ DENSITY      <chr> "Low", "Low", "Low", "Low", "Low", "High", "High", "High"…
$ RECRUITS     <dbl> 15, 10, 13, 13, 5, 11, 10, 15, 10, 13, 1, 21, 31, 21, 18,…
$ SQRTRECRUITS <dbl> 3.872983, 3.162278, 3.605551, 3.605551, 2.236068, 3.31662…
$ GROUP        <chr> "SpringLow", "SpringLow", "SpringLow", "SpringLow", "Spri…
## Explore the first 6 rows of the data
head(quinn)
# A tibble: 6 × 5
  SEASON DENSITY RECRUITS SQRTRECRUITS GROUP     
  <chr>  <chr>      <dbl>        <dbl> <chr>     
1 Spring Low           15         3.87 SpringLow 
2 Spring Low           10         3.16 SpringLow 
3 Spring Low           13         3.61 SpringLow 
4 Spring Low           13         3.61 SpringLow 
5 Spring Low            5         2.24 SpringLow 
6 Spring High          11         3.32 SpringHigh
str(quinn)
spc_tbl_ [42 × 5] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ SEASON      : chr [1:42] "Spring" "Spring" "Spring" "Spring" ...
 $ DENSITY     : chr [1:42] "Low" "Low" "Low" "Low" ...
 $ RECRUITS    : num [1:42] 15 10 13 13 5 11 10 15 10 13 ...
 $ SQRTRECRUITS: num [1:42] 3.87 3.16 3.61 3.61 2.24 ...
 $ GROUP       : chr [1:42] "SpringLow" "SpringLow" "SpringLow" "SpringLow" ...
 - attr(*, "spec")=
  .. cols(
  ..   SEASON = col_character(),
  ..   DENSITY = col_character(),
  ..   RECRUITS = col_double(),
  ..   SQRTRECRUITS = col_double(),
  ..   GROUP = col_character()
  .. )
 - attr(*, "problems")=<externalptr> 
quinn |> datawizard::data_codebook()
quinn (42 rows and 5 variables, 5 shown)

ID | Name         | Type      | Missings |     Values |          N
---+--------------+-----------+----------+------------+-----------
1  | SEASON       | character | 0 (0.0%) |     Autumn | 10 (23.8%)
   |              |           |          |     Spring | 11 (26.2%)
   |              |           |          |     Summer | 12 (28.6%)
   |              |           |          |     Winter |  9 (21.4%)
---+--------------+-----------+----------+------------+-----------
2  | DENSITY      | character | 0 (0.0%) |       High | 24 (57.1%)
   |              |           |          |        Low | 18 (42.9%)
---+--------------+-----------+----------+------------+-----------
3  | RECRUITS     | numeric   | 0 (0.0%) |    [0, 69] |         42
---+--------------+-----------+----------+------------+-----------
4  | SQRTRECRUITS | numeric   | 0 (0.0%) |  [0, 8.31] |         42
---+--------------+-----------+----------+------------+-----------
5  | GROUP        | character | 0 (0.0%) | AutumnHigh |  6 (14.3%)
   |              |           |          |  AutumnLow |  4 ( 9.5%)
   |              |           |          | SpringHigh |  6 (14.3%)
   |              |           |          |  SpringLow |  5 (11.9%)
   |              |           |          | SummerHigh |  6 (14.3%)
   |              |           |          |  SummerLow |  6 (14.3%)
   |              |           |          | WinterHigh |  6 (14.3%)
   |              |           |          |  WinterLow |  3 ( 7.1%)
------------------------------------------------------------------

4 Exploratory data analysis

Model formula: \[ \begin{align} y_i &\sim{} \mathcal{NB}(\lambda_i, \theta)\\ ln(\mu_i) &= \boldsymbol{\beta} \bf{X_i}\\ \beta_0 &\sim{} \mathcal{N}(0,10)\\ \beta_{1,2,3} &\sim{} \mathcal{N}(0,2.5)\\ \theta &\sim{} \mathcal{Exp}(1) \end{align} \]

where \(\boldsymbol{\beta}\) is a vector of effects parameters and \(\bf{X}\) is a model matrix representing the intercept and effects of season, density and their interaction on mussel recruitment.

quinn <- quinn |>
  mutate(SEASON = factor(SEASON,
                         levels = c("Spring", "Summer", "Autumn", "Winter")),
                         DENSITY = factor(DENSITY))

5 Exploratory data analysis

The exploratory data analyses that we performed in the frequentist instalment of this example are equally valid here. That is, boxplots and/or violin plots for each population (substrate type).

quinn |> head()
# A tibble: 6 × 5
  SEASON DENSITY RECRUITS SQRTRECRUITS GROUP     
  <fct>  <fct>      <dbl>        <dbl> <chr>     
1 Spring Low           15         3.87 SpringLow 
2 Spring Low           10         3.16 SpringLow 
3 Spring Low           13         3.61 SpringLow 
4 Spring Low           13         3.61 SpringLow 
5 Spring Low            5         2.24 SpringLow 
6 Spring High          11         3.32 SpringHigh
quinn |> ggplot(aes(y=RECRUITS, x=SEASON, fill=DENSITY)) + geom_boxplot()

Conclusions:

  • there is clearly a relationship between mean and variance (as would be expected with the a Poisson
  • evidently there are numerous zeros in the Winter/Low group # Fit the model

In rstanarm, the default priors are designed to be weakly informative. They are chosen to provide moderate regularisation (to help prevent over-fitting) and help stabilise the computations.

quinn.rstanarmP <- stan_glm(RECRUITS~SEASON*DENSITY,
                            data = quinn,
                            family = poisson(link = 'log'),
                            refresh = 0,
                            chains = 3, iter = 5000, thin = 5, warmup = 2000)
quinn.rstanarmP |> prior_summary()
Priors for model 'quinn.rstanarmP' 
------
Intercept (after predictors centered)
 ~ normal(location = 0, scale = 2.5)

Coefficients
  Specified prior:
    ~ normal(location = [0,0,0,...], scale = [2.5,2.5,2.5,...])
  Adjusted prior:
    ~ normal(location = [0,0,0,...], scale = [5.47,5.80,6.02,...])
------
See help('prior_summary.stanreg') for more details

This tells us:

  • for the intercept, when the family is Poisson, it is using a normal prior with a mean of 0 and a standard deviation of 2.5. The 2.5 is used for all intercepts. It is often scaled, but only if it is larger than 2.5 is the scaled version kept.

  • for the coefficients (in this case, the individual effects), the default prior is a normal prior centred around 0 with a standard deviations of 5.47, 5/8, 6.02 etc. This is then adjusted for the scale of the data by dividing the 2.5 by the standard deviation of the numerical dummy variables for the predictor (then rounded).

2.5/apply(model.matrix(~SEASON*DENSITY, quinn)[,-1], 2, sd)
           SEASONSummer            SEASONAutumn            SEASONWinter 
               5.467708                5.799380                6.019749 
             DENSITYLow SEASONSummer:DENSITYLow SEASONAutumn:DENSITYLow 
               4.991312                7.058781                8.414625 
SEASONWinter:DENSITYLow 
               9.590995 
  • there is no auxiliary prior as we are employing a Poisson distribution.
quinn.rstanarm1 <- stan_glm(RECRUITS~SEASON*DENSITY, data = quinn,
                            family = poisson(link = 'log'),
                            prior_PD = TRUE, 
                            refresh = 0,
                            chains = 3, iter = 5000, thin = 5, warmup = 2000)
quinn.rstanarm1 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data = TRUE)

quinn.rstanarm1 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data = TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.
Warning: Transformation introduced infinite values in continuous y-axis

## although, since there are zeros...
quinn.rstanarm1 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data = TRUE, jitter = FALSE) |>
    wrap_plots() &
    scale_y_continuous(trans = scales::pseudo_log_trans())
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

quinn.rstanarm1 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data=TRUE) |>
    plot(add.data = TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

Warning: Transformation introduced infinite values in continuous y-axis

## although, since there are zeros...
quinn.rstanarm1 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data = TRUE, jitter = FALSE) |>
    wrap_plots() &
    scale_y_continuous(trans = scales::pseudo_log_trans())
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

Conclusions:

  • we see that the range of predictions is fairly wide and the predicted means could range from 0 to very large (perhaps too large).

The following link provides some guidance about defining priors. [https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations]

When defining our own priors, we typically do not want them to be scaled.

If we wanted to define our own priors that were less vague, yet still not likely to bias the outcomes, we could try the following priors (mainly plucked out of thin air):

  • \(\beta_0\): normal centred at 2.3 with a standard deviation of 5
  • \(\beta_1\): normal centred at 0 with a standard deviation of 2

Remember the above are applied on the link scale.

I will also overlay the raw data for comparison.

quinn |> group_by(SEASON, DENSITY) |>
    summarise(Mean = log(mean(RECRUITS)),
              SD = log(sd(RECRUITS)))
`summarise()` has grouped output by 'SEASON'. You can override using the
`.groups` argument.
# A tibble: 8 × 4
# Groups:   SEASON [4]
  SEASON DENSITY  Mean    SD
  <fct>  <fct>   <dbl> <dbl>
1 Spring High    2.30   1.57
2 Spring Low     2.42   1.36
3 Summer High    3.87   2.71
4 Summer Low     3.09   1.81
5 Autumn High    2.98   2.48
6 Autumn Low     2.90   1.13
7 Winter High    1.73   1.20
8 Winter Low     0.981  1.53
log(sd(quinn$RECRUITS))/
    apply(model.matrix(~SEASON*DENSITY, data = quinn), 2, sd)
            (Intercept)            SEASONSummer            SEASONAutumn 
                    Inf                6.024998                6.390475 
           SEASONWinter              DENSITYLow SEASONSummer:DENSITYLow 
               6.633304                5.500045                7.778238 
SEASONAutumn:DENSITYLow SEASONWinter:DENSITYLow 
               9.272276               10.568545 
quinn.rstanarm2 <- stan_glm(RECRUITS~SEASON*DENSITY, data = quinn,
                            family = poisson(link = 'log'),
                            prior_intercept = normal(2.3, 2, autoscale = FALSE),
                            prior = normal(0, 10, autoscale = FALSE),
                            prior_PD = TRUE, 
                            refresh = 0,
                            chains = 3, iter = 5000, thin = 5, warmup = 2000)
quinn.rstanarm2 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data = TRUE)

quinn.rstanarm2 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data = TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.
Warning: Transformation introduced infinite values in continuous y-axis

## although, since there are zeros...
quinn.rstanarm2 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data = TRUE, jitter = FALSE) |>
    wrap_plots() &
    scale_y_continuous(trans = scales::pseudo_log_trans())
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

quinn.rstanarm2 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data=TRUE) |>
    plot(add.data = TRUE) |>
    wrap_plots() &
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

Warning: Transformation introduced infinite values in continuous y-axis

## although, since there are zeros...
quinn.rstanarm2 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data = TRUE, jitter = FALSE) |>
    wrap_plots() &
    scale_y_continuous(trans = scales::pseudo_log_trans())
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

Now lets refit, conditioning on the data.

quinn.rstanarm3 <- quinn.rstanarm2 |> update(prior_PD = FALSE) 
quinn.rstanarm3 |> posterior_vs_prior(color_by = 'vs', group_by = TRUE,
                   facet_args = list(scales = 'free_y'))

Drawing from prior...

Conclusions:

  • in each case, the prior is substantially wider than the posterior, suggesting that the posterior is not biased towards the prior.
quinn.rstanarm3 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data = TRUE)

quinn.rstanarm3 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data=TRUE) 

In brms, the default priors are designed to be weakly informative. They are chosen to provide moderate regularisation (to help prevent over-fitting) and help stabilise the computations.

Unlike rstanarm, brms models must be compiled before they start sampling. For most models, the compilation of the stan code takes around 45 seconds.

quinn.form <- bf(RECRUITS ~ SEASON*DENSITY,  family = poisson(link = 'log'))
get_prior(quinn.form,  data = quinn)
                  prior     class                    coef group resp dpar nlpar lb ub       source
                 (flat)         b                                                          default
                 (flat)         b              DENSITYLow                             (vectorized)
                 (flat)         b            SEASONAutumn                             (vectorized)
                 (flat)         b SEASONAutumn:DENSITYLow                             (vectorized)
                 (flat)         b            SEASONSummer                             (vectorized)
                 (flat)         b SEASONSummer:DENSITYLow                             (vectorized)
                 (flat)         b            SEASONWinter                             (vectorized)
                 (flat)         b SEASONWinter:DENSITYLow                             (vectorized)
 student_t(3, 2.6, 2.5) Intercept                                                          default

Remember that the priors are applied on the link (in this case, log) scale.

quinn |>
    group_by(SEASON, DENSITY) |>
    summarise(Mean = mean(RECRUITS),
              Median = median(RECRUITS),
              MAD = mad(RECRUITS),
              SD = sd(RECRUITS)) |>
    mutate(log(Mean),
           log(Median),
           log(MAD),
           log(SD))
`summarise()` has grouped output by 'SEASON'. You can override using the
`.groups` argument.
# A tibble: 8 × 10
# Groups:   SEASON [4]
  SEASON DENSITY  Mean Median   MAD    SD `log(Mean)` `log(Median)` `log(MAD)`
  <fct>  <fct>   <dbl>  <dbl> <dbl> <dbl>       <dbl>         <dbl>      <dbl>
1 Spring High    10      10.5  2.22  4.82       2.30           2.35      0.799
2 Spring Low     11.2    13    2.97  3.90       2.42           2.56      1.09 
3 Summer High    48.2    51.5 15.6  15.0        3.87           3.94      2.75 
4 Summer Low     22      21    6.67  6.13       3.09           3.04      1.90 
5 Autumn High    19.7    17.5 12.6  11.9        2.98           2.86      2.53 
6 Autumn Low     18.2    19    2.22  3.10       2.90           2.94      0.799
7 Winter High     5.67    5    3.71  3.33       1.73           1.61      1.31 
8 Winter Low      2.67    0    0     4.62       0.981       -Inf      -Inf    
# ℹ 1 more variable: `log(SD)` <dbl>
  • \(\beta_0\): normal centred at 2.3 with a standard deviation of 1.5
  • \(\beta_1\): normal centred at 0 with a standard deviation of 1
priors <- prior(normal(2.4, 1.5), class = 'Intercept') +
    prior(normal(0, 1), class = 'b') 
quinn.brm2 <- brm(quinn.form,
                  data = quinn,
                  prior = priors,
                  sample_prior = "only",
                  refresh = 0,
                  chains = 3,
                  iter = 5000,
                  thin = 5,
                  warmup = 2500,
                  backend = 'cmdstanr') 
Start sampling
Running MCMC with 3 sequential chains...

Chain 1 finished in 0.0 seconds.
Chain 2 finished in 0.0 seconds.
Chain 3 finished in 0.0 seconds.

All 3 chains finished successfully.
Mean chain execution time: 0.0 seconds.
Total execution time: 0.5 seconds.
quinn.brm2 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data=TRUE)

quinn.brm2 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data=TRUE) +
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.
Warning: Transformation introduced infinite values in continuous y-axis

## Or since there are zeros
quinn.brm2 |>
    ggpredict(~SEASON+DENSITY) |>
    plot(add.data=TRUE) +
    scale_y_continuous(trans = scales::pseudo_log_trans())
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

quinn.brm2 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data=TRUE)

quinn.brm2 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data=TRUE) +
    scale_y_log10()
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.
Warning: Transformation introduced infinite values in continuous y-axis

## Or since there are zeros
quinn.brm2 |>
    ggemmeans(~SEASON+DENSITY) |>
    plot(add.data=TRUE) +
    scale_y_continuous(trans = scales::pseudo_log_trans())
Scale for y is already present.
Adding another scale for y, which will replace the existing scale.

quinn.brm2 |>
    conditional_effects('SEASON:DENSITY') |>
    plot(points=TRUE)

quinn.brm2 |>
    conditional_effects('SEASON:DENSITY') |>
    plot(points=TRUE) |>
    wrap_plots() &
    scale_y_continuous(trans = scales::pseudo_log_trans())

quinn.brmP <- quinn.brm2 |> update(sample_prior = 'yes', refresh = 0)
The desired updates require recompiling the model
Start sampling
Running MCMC with 3 sequential chains...

Chain 1 finished in 0.2 seconds.
Chain 2 finished in 0.2 seconds.
Chain 3 finished in 0.2 seconds.

All 3 chains finished successfully.
Mean chain execution time: 0.2 seconds.
Total execution time: 0.8 seconds.
quinn.brmP |> get_variables()
 [1] "b_Intercept"               "b_SEASONSummer"           
 [3] "b_SEASONAutumn"            "b_SEASONWinter"           
 [5] "b_DENSITYLow"              "b_SEASONSummer:DENSITYLow"
 [7] "b_SEASONAutumn:DENSITYLow" "b_SEASONWinter:DENSITYLow"
 [9] "prior_Intercept"           "prior_b"                  
[11] "lprior"                    "lp__"                     
[13] "accept_stat__"             "treedepth__"              
[15] "stepsize__"                "divergent__"              
[17] "n_leapfrog__"              "energy__"                 
quinn.brmP |> hypothesis('SEASONSummer<0') |> plot()

quinn.brmP |> hypothesis('DENSITYLow<0') |> plot()

quinn.brmP |> hypothesis('SEASONSummer:DENSITYLow<0') |> plot()

quinn.brmP |> SUYR_prior_and_posterior()

quinn.brmP |>
  posterior_samples() |>
  dplyr::select(-`lp__`) |>
  pivot_longer(everything(), names_to = 'key') |> 
  mutate(Type = ifelse(str_detect(key, 'prior'), 'Prior', 'b'),
         Class = ifelse(str_detect(key, 'Intercept'),  'Intercept',
               ifelse(str_detect(key, 'b'),  'b', 'sigma')),
         Par = str_replace(key, 'b_', '')) |>
  ggplot(aes(x = Type,  y = value, color = Par)) +
  stat_pointinterval(position = position_dodge())+
  facet_wrap(~Class,  scales = 'free')
Warning: Method 'posterior_samples' is deprecated. Please see ?as_draws for
recommended alternatives.

quinn.brmP |> standata()
$N
[1] 42

$Y
 [1] 15 10 13 13  5 11 10 15 10 13  1 21 31 21 18 14 27 34 49 69 55 28 54 14 18
[26] 20 21  4 22 30 36 13 13  8  0  0 10  1  5  9  4  5

$K
[1] 8

$X
   Intercept SEASONSummer SEASONAutumn SEASONWinter DENSITYLow
1          1            0            0            0          1
2          1            0            0            0          1
3          1            0            0            0          1
4          1            0            0            0          1
5          1            0            0            0          1
6          1            0            0            0          0
7          1            0            0            0          0
8          1            0            0            0          0
9          1            0            0            0          0
10         1            0            0            0          0
11         1            0            0            0          0
12         1            1            0            0          1
13         1            1            0            0          1
14         1            1            0            0          1
15         1            1            0            0          1
16         1            1            0            0          1
17         1            1            0            0          1
18         1            1            0            0          0
19         1            1            0            0          0
20         1            1            0            0          0
21         1            1            0            0          0
22         1            1            0            0          0
23         1            1            0            0          0
24         1            0            1            0          1
25         1            0            1            0          1
26         1            0            1            0          1
27         1            0            1            0          1
28         1            0            1            0          0
29         1            0            1            0          0
30         1            0            1            0          0
31         1            0            1            0          0
32         1            0            1            0          0
33         1            0            1            0          0
34         1            0            0            1          1
35         1            0            0            1          1
36         1            0            0            1          1
37         1            0            0            1          0
38         1            0            0            1          0
39         1            0            0            1          0
40         1            0            0            1          0
41         1            0            0            1          0
42         1            0            0            1          0
   SEASONSummer:DENSITYLow SEASONAutumn:DENSITYLow SEASONWinter:DENSITYLow
1                        0                       0                       0
2                        0                       0                       0
3                        0                       0                       0
4                        0                       0                       0
5                        0                       0                       0
6                        0                       0                       0
7                        0                       0                       0
8                        0                       0                       0
9                        0                       0                       0
10                       0                       0                       0
11                       0                       0                       0
12                       1                       0                       0
13                       1                       0                       0
14                       1                       0                       0
15                       1                       0                       0
16                       1                       0                       0
17                       1                       0                       0
18                       0                       0                       0
19                       0                       0                       0
20                       0                       0                       0
21                       0                       0                       0
22                       0                       0                       0
23                       0                       0                       0
24                       0                       1                       0
25                       0                       1                       0
26                       0                       1                       0
27                       0                       1                       0
28                       0                       0                       0
29                       0                       0                       0
30                       0                       0                       0
31                       0                       0                       0
32                       0                       0                       0
33                       0                       0                       0
34                       0                       0                       1
35                       0                       0                       1
36                       0                       0                       1
37                       0                       0                       0
38                       0                       0                       0
39                       0                       0                       0
40                       0                       0                       0
41                       0                       0                       0
42                       0                       0                       0
attr(,"assign")
[1] 0 1 1 1 2 3 3 3
attr(,"contrasts")
attr(,"contrasts")$SEASON
       Summer Autumn Winter
Spring      0      0      0
Summer      1      0      0
Autumn      0      1      0
Winter      0      0      1

attr(,"contrasts")$DENSITY
     Low
High   0
Low    1


$prior_only
[1] 0

attr(,"class")
[1] "standata" "list"    
quinn.brmP |> stancode()
// generated with brms 2.19.0
functions {
  
}
data {
  int<lower=1> N; // total number of observations
  array[N] int Y; // response variable
  int<lower=1> K; // number of population-level effects
  matrix[N, K] X; // population-level design matrix
  int prior_only; // should the likelihood be ignored?
}
transformed data {
  int Kc = K - 1;
  matrix[N, Kc] Xc; // centered version of X without an intercept
  vector[Kc] means_X; // column means of X before centering
  for (i in 2 : K) {
    means_X[i - 1] = mean(X[ : , i]);
    Xc[ : , i - 1] = X[ : , i] - means_X[i - 1];
  }
}
parameters {
  vector[Kc] b; // population-level effects
  real Intercept; // temporary intercept for centered predictors
}
transformed parameters {
  real lprior = 0; // prior contributions to the log posterior
  lprior += normal_lpdf(b | 0, 1);
  lprior += normal_lpdf(Intercept | 2.4, 1.5);
}
model {
  // likelihood including constants
  if (!prior_only) {
    target += poisson_log_glm_lpmf(Y | Xc, Intercept, b);
  }
  // priors including constants
  target += lprior;
}
generated quantities {
  // actual population-level intercept
  real b_Intercept = Intercept - dot_product(means_X, b);
  // additionally sample draws from priors
  real prior_b = normal_rng(0, 1);
  real prior_Intercept = normal_rng(2.4, 1.5);
}

6 MCMC sampling diagnostics

The bayesplot package offers a range of MCMC diagnostics as well as Posterior Probability Checks (PPC), all of which have a convenient plot() interface. Lets start with the MCMC diagnostics.

available_mcmc()
bayesplot MCMC module:
  mcmc_acf
  mcmc_acf_bar
  mcmc_areas
  mcmc_areas_ridges
  mcmc_combo
  mcmc_dens
  mcmc_dens_chains
  mcmc_dens_overlay
  mcmc_hex
  mcmc_hist
  mcmc_hist_by_chain
  mcmc_intervals
  mcmc_neff
  mcmc_neff_hist
  mcmc_nuts_acceptance
  mcmc_nuts_divergence
  mcmc_nuts_energy
  mcmc_nuts_stepsize
  mcmc_nuts_treedepth
  mcmc_pairs
  mcmc_parcoord
  mcmc_rank_ecdf
  mcmc_rank_hist
  mcmc_rank_overlay
  mcmc_recover_hist
  mcmc_recover_intervals
  mcmc_recover_scatter
  mcmc_rhat
  mcmc_rhat_hist
  mcmc_scatter
  mcmc_trace
  mcmc_trace_highlight
  mcmc_violin

Of these, we will focus on:

  • mcmc_trace: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different shade of blue, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
plot(quinn.rstanarm3, plotfun='mcmc_trace')

The chains appear well mixed and very similar

  • acf (auto-correlation function): plots the auto-correlation between successive MCMC sample lags for each parameter and each chain
plot(quinn.rstanarm3, 'acf_bar')
Warning: The `facets` argument of `facet_grid()` is deprecated as of ggplot2 2.2.0.
ℹ Please use the `rows` argument instead.
ℹ The deprecated feature was likely used in the bayesplot package.
  Please report the issue at <https://github.com/stan-dev/bayesplot/issues/>.

There is no evidence of auto-correlation in the MCMC samples

  • Rhat: Rhat is a measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
plot(quinn.rstanarm3, 'rhat_hist')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

All Rhat values are below 1.05, suggesting the chains have converged.

  • neff (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

plot(quinn.rstanarm3, 'neff_hist')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Ratios all very high.

More diagnostics
plot(quinn.rstanarm3, 'combo')

plot(quinn.rstanarm3, 'violin')

The rstan package offers a range of MCMC diagnostics. Lets start with the MCMC diagnostics.

Of these, we will focus on:

  • stan_trace: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different colour, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
stan_trace(quinn.rstanarm3)

The chains appear well mixed and very similar

  • stan_acf (autocorrelation function): plots the autocorrelation between successive MCMC sample lags for each parameter and each chain
stan_ac(quinn.rstanarm3) 

There is no evidence of auto-correlation in the MCMC samples

  • stan_rhat: Rhat is a scale reduction factor measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
stan_rhat(quinn.rstanarm3) 
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

All Rhat values are below 1.05, suggesting the chains have converged.

  • stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

stan_ess(quinn.rstanarm3)
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Ratios all very high.

stan_dens(quinn.rstanarm3, separate_chains = TRUE)

The ggmean package also has a set of MCMC diagnostic functions. Lets start with the MCMC diagnostics.

Of these, we will focus on:

  • ggs_traceplot: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different colour, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
quinn.ggs <- ggs(quinn.rstanarm3, burnin = FALSE, inc_warmup = FALSE)
ggs_traceplot(quinn.ggs)

The chains appear well mixed and very similar

  • gss_autocorrelation (autocorrelation function): plots the autocorrelation between successive MCMC sample lags for each parameter and each chain
ggs_autocorrelation(quinn.ggs)

There is no evidence of auto-correlation in the MCMC samples

  • stan_rhat: Rhat is a scale reduction factor measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
ggs_Rhat(quinn.ggs)

All Rhat values are below 1.05, suggesting the chains have converged.

  • stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

ggs_effective(quinn.ggs)
Warning: Returning more (or less) than 1 row per `summarise()` group was deprecated in
dplyr 1.1.0.
ℹ Please use `reframe()` instead.
ℹ When switching from `summarise()` to `reframe()`, remember that `reframe()`
  always returns an ungrouped data frame and adjust accordingly.
ℹ The deprecated feature was likely used in the ggmcmc package.
  Please report the issue at <https://github.com/xfim/ggmcmc/issues/>.

Ratios all very high.

More diagnostics
ggs_crosscorrelation(quinn.ggs)

ggs_grb(quinn.ggs)

The brms package offers a range of MCMC diagnostics. Lets start with the MCMC diagnostics.

Of these, we will focus on:

  • stan_trace: this plots the estimates of each parameter over the post-warmup length of each MCMC chain. Each chain is plotted in a different colour, with each parameter in its own facet. Ideally, each trace should just look like noise without any discernible drift and each of the traces for a specific parameter should look the same (i.e, should not be displaced above or below any other trace for that parameter).
quinn.brmP$fit |> stan_trace()
'pars' not specified. Showing first 10 parameters by default.

quinn.brmP$fit |> stan_trace(inc_warmup=TRUE)
'pars' not specified. Showing first 10 parameters by default.

The chains appear well mixed and very similar

  • stan_acf (auto-correlation function): plots the auto-correlation between successive MCMC sample lags for each parameter and each chain
quinn.brmP$fit |> stan_ac() 
'pars' not specified. Showing first 10 parameters by default.

There is no evidence of auto-correlation in the MCMC samples

  • stan_rhat: Rhat is a scale reduction factor measure of convergence between the chains. The closer the values are to 1, the more the chains have converged. Values greater than 1.05 indicate a lack of convergence. There will be an Rhat value for each parameter estimated.
quinn.brmP$fit |> stan_rhat() 
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

All Rhat values are below 1.05, suggesting the chains have converged.

  • stan_ess (number of effective samples): the ratio of the number of effective samples (those not rejected by the sampler) to the number of samples provides an indication of the effectiveness (and efficiency) of the MCMC sampler. Ratios that are less than 0.5 for a parameter suggest that the sampler spent considerable time in difficult areas of the sampling domain and rejected more than half of the samples (replacing them with the previous effective sample).

    If the ratios are low, tightening the priors may help.

quinn.brmP$fit |> stan_ess()
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Ratios all very high.

quinn.brmP$fit |> stan_dens(separate_chains = TRUE)
'pars' not specified. Showing first 10 parameters by default.

7 Model validation

Post predictive checks provide additional diagnostics about the fit of the model. Specifically, they provide a comparison between predictions drawn from the model and the observed data used to train the model.

available_ppc()
bayesplot PPC module:
  ppc_bars
  ppc_bars_grouped
  ppc_boxplot
  ppc_dens
  ppc_dens_overlay
  ppc_dens_overlay_grouped
  ppc_ecdf_overlay
  ppc_ecdf_overlay_grouped
  ppc_error_binned
  ppc_error_hist
  ppc_error_hist_grouped
  ppc_error_scatter
  ppc_error_scatter_avg
  ppc_error_scatter_avg_grouped
  ppc_error_scatter_avg_vs_x
  ppc_freqpoly
  ppc_freqpoly_grouped
  ppc_hist
  ppc_intervals
  ppc_intervals_grouped
  ppc_km_overlay
  ppc_km_overlay_grouped
  ppc_loo_intervals
  ppc_loo_pit
  ppc_loo_pit_overlay
  ppc_loo_pit_qq
  ppc_loo_ribbon
  ppc_pit_ecdf
  ppc_pit_ecdf_grouped
  ppc_ribbon
  ppc_ribbon_grouped
  ppc_rootogram
  ppc_scatter
  ppc_scatter_avg
  ppc_scatter_avg_grouped
  ppc_stat
  ppc_stat_2d
  ppc_stat_freqpoly
  ppc_stat_freqpoly_grouped
  ppc_stat_grouped
  ppc_violin_grouped
  • dens_overlay: plots the density distribution of the observed data (black line) overlayed on top of 50 density distributions generated from draws from the model (light blue). Ideally, the 50 realisations should be roughly consistent with the observed data.
pp_check(quinn.rstanarm3,  plotfun='dens_overlay')

The model draws are broadly similar to the observed data.

  • error_scatter_avg: this plots the observed values against the average residuals. Similar to a residual plot, we do not want to see any patterns in this plot. There is some pattern remaining in these residuals.
pp_check(quinn.rstanarm3, plotfun='error_scatter_avg')

The predictive error seems to be related to the predictor - the model performs poorest at higher recruitments

  • error_scatter_avg_vs_x: this is similar to a regular residual plot and as such should be interpreted as such.
pp_check(quinn.rstanarm3, x=as.numeric(quinn$SEASON), plotfun='error_scatter_avg_vs_x')

pp_check(quinn.rstanarm3, x=as.numeric(quinn$DENSITY), plotfun='error_scatter_avg_vs_x')

  • intervals: plots the observed data overlayed on top of posterior predictions associated with each level of the predictor. Ideally, the observed data should all fall within the predictive intervals.
pp_check(quinn.rstanarm3, x=as.numeric(quinn$SEASON), plotfun='intervals')

The modelled predictions seem to do a reasonable job of representing the observations.

The shinystan package allows the full suite of MCMC diagnostics and posterior predictive checks to be accessed via a web interface.

#library(shinystan)
#launch_shinystan(quinn.rstanarm3)

DHARMa residuals provide very useful diagnostics. Unfortunately, we cannot directly use the simulateResiduals() function to generate the simulated residuals. However, if we are willing to calculate some of the components yourself, we can still obtain the simulated residuals from the fitted stan model.

We need to supply:

  • simulated (predicted) responses associated with each observation.
  • observed values
  • fitted (predicted) responses (averaged) associated with each observation
preds <- posterior_predict(quinn.rstanarm3,  nsamples=250,  summary=FALSE)
quinn.resids <- createDHARMa(simulatedResponse = t(preds),
                            observedResponse = quinn$RECRUITS,
                            fittedPredictedResponse = apply(preds, 2, median),
                            integerResponse = TRUE)
plot(quinn.resids)

Conclusions:

  • the simulated residuals suggest there might be an issue of dispersion.
  • it might be worth exploring either zero-inflation, a negative binomial model, or including a observation-level random effect.

Post predictive checks provide additional diagnostics about the fit of the model. Specifically, they provide a comparison between predictions drawn from the model and the observed data used to train the model.

available_ppc()
bayesplot PPC module:
  ppc_bars
  ppc_bars_grouped
  ppc_boxplot
  ppc_dens
  ppc_dens_overlay
  ppc_dens_overlay_grouped
  ppc_ecdf_overlay
  ppc_ecdf_overlay_grouped
  ppc_error_binned
  ppc_error_hist
  ppc_error_hist_grouped
  ppc_error_scatter
  ppc_error_scatter_avg
  ppc_error_scatter_avg_grouped
  ppc_error_scatter_avg_vs_x
  ppc_freqpoly
  ppc_freqpoly_grouped
  ppc_hist
  ppc_intervals
  ppc_intervals_grouped
  ppc_km_overlay
  ppc_km_overlay_grouped
  ppc_loo_intervals
  ppc_loo_pit
  ppc_loo_pit_overlay
  ppc_loo_pit_qq
  ppc_loo_ribbon
  ppc_pit_ecdf
  ppc_pit_ecdf_grouped
  ppc_ribbon
  ppc_ribbon_grouped
  ppc_rootogram
  ppc_scatter
  ppc_scatter_avg
  ppc_scatter_avg_grouped
  ppc_stat
  ppc_stat_2d
  ppc_stat_freqpoly
  ppc_stat_freqpoly_grouped
  ppc_stat_grouped
  ppc_violin_grouped
  • dens_overlay: plots the density distribution of the observed data (black line) overlayed on top of 50 density distributions generated from draws from the model (light blue). Ideally, the 50 realisations should be roughly consistent with the observed data.
quinn.brmP |> pp_check(type = 'dens_overlay', ndraws = 100)

The model draws appear to represent the shape of the observed data reasonably well

  • error_scatter_avg: this plots the observed values against the average residuals. Similar to a residual plot, we do not want to see any patterns in this plot. There is some pattern remaining in these residuals.
quinn.brmP |> pp_check(type = 'error_scatter_avg')
Using all posterior draws for ppc type 'error_scatter_avg' by default.

The predictive error seems to be related to the predictor - the model performs poorest at higher recruitments.

  • intervals: plots the observed data overlayed on top of posterior predictions associated with each level of the predictor. Ideally, the observed data should all fall within the predictive intervals.
quinn.brmP |> pp_check(type='intervals')
Using all posterior draws for ppc type 'intervals' by default.

## quinn.brmP |> pp_check(group='DENSITY', type='intervals')

Whilst the modelled predictions do a reasonable job of representing the observed data, the observed data do appear to be more varied than the model is representing.

The shinystan package allows the full suite of MCMC diagnostics and posterior predictive checks to be accessed via a web interface.

#library(shinystan)
#launch_shinystan(quinn.brmP)

DHARMa residuals provide very useful diagnostics. Unfortunately, we cannot directly use the simulateResiduals() function to generate the simulated residuals. However, if we are willing to calculate some of the components yourself, we can still obtain the simulated residuals from the fitted stan model.

We need to supply:

  • simulated (predicted) responses associated with each observation.
  • observed values
  • fitted (predicted) responses (averaged) associated with each observation
preds <- quinn.brmP |> posterior_predict(nsamples = 250,  summary = FALSE)
Warning: Argument 'nsamples' is deprecated. Please use argument 'ndraws'
instead.
quinn.resids <- createDHARMa(simulatedResponse = t(preds),
                            observedResponse = quinn$RECRUITS,
                            fittedPredictedResponse = apply(preds, 2, median),
                            integerResponse = TRUE)
quinn.resids |> plot()

quinn.resids |> testDispersion()


    DHARMa nonparametric dispersion test via sd of residuals fitted vs.
    simulated

data:  simulationOutput
dispersion = 2.7284, p-value < 2.2e-16
alternative hypothesis: two.sided
quinn.resids |> testZeroInflation()


    DHARMa zero-inflation test via comparison to expected zeros with
    simulation under H0 = fitted model

data:  simulationOutput
ratioObsSim = 8.7719, p-value = 0.056
alternative hypothesis: two.sided
quinn.resids <- make_brms_dharma_res(quinn.brmP, integerResponse = TRUE)
wrap_elements(~testUniformity(quinn.resids)) +
               wrap_elements(~plotResiduals(quinn.resids, form = factor(rep(1, nrow(quinn))))) +
               wrap_elements(~plotResiduals(quinn.resids, quantreg = TRUE)) +
               wrap_elements(~testDispersion(quinn.resids))

Conclusions:

  • the simulated residuals do suggest that there might be a dispersion issue
  • it might be worth exploring either zero-inflation, a negative binomial model, or including a observation-level random effect.

8 Explore negative binomial model

quinn.rstanarmNB <- stan_glm(RECRUITS~SEASON*DENSITY, data = quinn,
                            family = neg_binomial_2(link = 'log'),
                            prior_intercept = normal(2.3, 2, autoscale = FALSE),
                            prior = normal(0, 10, autoscale = FALSE),
                            prior_aux = rstanarm::exponential(rate = 1, autoscale = FALSE),
                            prior_PD = FALSE, 
                            refresh = 0,
                            chains = 3, iter = 5000, thin = 5, warmup = 2000)
posterior_vs_prior(quinn.rstanarmNB, color_by='vs', group_by=TRUE,
                   facet_args=list(scales='free_y'))

Drawing from prior...

quinn.rstanarmNB |> ggpredict(~SEASON+DENSITY) |> plot(add.data = TRUE)

quinn.rstanarmNB |>
    ggemmeans(~SEASON+DENSITY, back.transform = TRUE) |>
    plot(add.data=TRUE)

There seems to be a bug here. The expected values should be being back transformed to the response scale, however, they are clearly not. Notice that the expected values (and associated CI) are low and tiny respectively).

quinn.rstanarmNB |> plot('mcmc_trace')

quinn.rstanarmNB |> plot('mcmc_acf_bar')
Warning: The `facets` argument of `facet_grid()` is deprecated as of ggplot2 2.2.0.
ℹ Please use the `rows` argument instead.
ℹ The deprecated feature was likely used in the bayesplot package.
  Please report the issue at <https://github.com/stan-dev/bayesplot/issues/>.

quinn.rstanarmNB |> plot('mcmc_rhat_hist')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

quinn.rstanarmNB |> plot('mcmc_neff_hist')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

preds <- posterior_predict(quinn.rstanarmNB,  nsamples=250,  summary=FALSE)
quinn.resids <- createDHARMa(simulatedResponse = t(preds),
                            observedResponse = quinn$RECRUITS,
                            fittedPredictedResponse = apply(preds, 2, median),
                            integerResponse=TRUE)
plot(quinn.resids)

quinn.resids |> testDispersion()


    DHARMa nonparametric dispersion test via sd of residuals fitted vs.
    simulated

data:  simulationOutput
dispersion = 0.25325, p-value = 0.03556
alternative hypothesis: two.sided

Now possibly under-dispersed..

(loo.P = loo(quinn.rstanarmP))
Warning: Found 1 observation(s) with a pareto_k > 0.7. We recommend calling 'loo' again with argument 'k_threshold = 0.7' in order to calculate the ELPD without the assumption that these observations are negligible. This will refit the model 1 times to compute the ELPDs for the problematic observations directly.

Computed from 1800 by 42 log-likelihood matrix

         Estimate   SE
elpd_loo   -170.4 15.4
p_loo        23.7  5.4
looic       340.9 30.9
------
Monte Carlo SE of elpd_loo is NA.

Pareto k diagnostic values:
                         Count Pct.    Min. n_eff
(-Inf, 0.5]   (good)     34    81.0%   289       
 (0.5, 0.7]   (ok)        7    16.7%   113       
   (0.7, 1]   (bad)       1     2.4%   10        
   (1, Inf)   (very bad)  0     0.0%   <NA>      
See help('pareto-k-diagnostic') for details.
(loo.NB = loo(quinn.rstanarmNB))
Warning: Found 1 observation(s) with a pareto_k > 0.7. We recommend calling 'loo' again with argument 'k_threshold = 0.7' in order to calculate the ELPD without the assumption that these observations are negligible. This will refit the model 1 times to compute the ELPDs for the problematic observations directly.

Computed from 1800 by 42 log-likelihood matrix

         Estimate   SE
elpd_loo   -150.7  5.9
p_loo         9.4  3.4
looic       301.3 11.8
------
Monte Carlo SE of elpd_loo is NA.

Pareto k diagnostic values:
                         Count Pct.    Min. n_eff
(-Inf, 0.5]   (good)     37    88.1%   590       
 (0.5, 0.7]   (ok)        4     9.5%   554       
   (0.7, 1]   (bad)       0     0.0%   <NA>      
   (1, Inf)   (very bad)  1     2.4%   8         
See help('pareto-k-diagnostic') for details.
loo_compare(loo.P, loo.NB)
                 elpd_diff se_diff
quinn.rstanarmNB   0.0       0.0  
quinn.rstanarmP  -19.8      11.8  
quinn.form <- bf(RECRUITS ~ SEASON*DENSITY,  family = negbinomial(link = 'log'))
get_prior(quinn.form,  data = quinn)
                  prior     class                    coef group resp dpar nlpar
                 (flat)         b                                              
                 (flat)         b              DENSITYLow                      
                 (flat)         b            SEASONAutumn                      
                 (flat)         b SEASONAutumn:DENSITYLow                      
                 (flat)         b            SEASONSummer                      
                 (flat)         b SEASONSummer:DENSITYLow                      
                 (flat)         b            SEASONWinter                      
                 (flat)         b SEASONWinter:DENSITYLow                      
 student_t(3, 2.6, 2.5) Intercept                                              
      gamma(0.01, 0.01)     shape                                              
 lb ub       source
            default
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
            default
  0         default
priors <- prior(normal(2.4, 1.5), class = 'Intercept') +
    prior(normal(0, 1), class = 'b') +
    prior(gamma(0.01, 0.01), class = "shape")
quinn.brmsNB <- brm(quinn.form,
                    data = quinn,
                    prior = priors,
                    refresh = 0,
                    chains = 3,
                    iter = 5000,
                    thin = 5,
                    warmup = 2500,
                    backend = "cmdstanr") 
Start sampling
Running MCMC with 3 sequential chains...

Chain 1 finished in 0.2 seconds.
Chain 2 finished in 0.3 seconds.
Chain 3 finished in 0.3 seconds.

All 3 chains finished successfully.
Mean chain execution time: 0.3 seconds.
Total execution time: 1.0 seconds.
preds <- posterior_predict(quinn.brmsNB,  nsamples = 250,  summary = FALSE)
Warning: Argument 'nsamples' is deprecated. Please use argument 'ndraws'
instead.
quinn.resids <- createDHARMa(simulatedResponse = t(preds),
                            observedResponse = quinn$RECRUITS,
                            fittedPredictedResponse = apply(preds, 2, median),
                            integerResponse = TRUE)
plot(quinn.resids)

quinn.resids <- make_brms_dharma_res(quinn.brmsNB, integerResponse = TRUE)
wrap_elements(~testUniformity(quinn.resids)) +
               ## wrap_elements(~plotResiduals(quinn.resids, form = factor(rep(1, nrow(quinn))))) +
               wrap_elements(~plotResiduals(quinn.resids, quantreg = TRUE)) +
               wrap_elements(~testDispersion(quinn.resids))

9 Partial effects plots

quinn.rstanarmNB |> ggpredict(~SEASON+DENSITY) |> plot(add.data=TRUE)

quinn.rstanarmNB |>
    ggemmeans(~SEASON|DENSITY,  type='fixed', back.transform = TRUE) |>
    plot(add.data=TRUE)

quinn.rstanarmNB |>
    fitted_draws(newdata=quinn) |>
    median_hdci() |>
    ggplot(aes(x=SEASON, colour=DENSITY, y=.value)) +
    geom_pointrange(aes(ymin=.lower, ymax=.upper), position = position_dodge(width=0.2)) + 
    geom_line(position = position_dodge(width=0.2)) +
    geom_point(data=quinn,  aes(y=RECRUITS,  x=SEASON, colour = DENSITY), position = position_dodge(width=0.2))
Warning: `fitted_draws` and `add_fitted_draws` are deprecated as their names were confusing.
Use [add_]epred_draws() to get the expectation of the posterior predictive.
Use [add_]linpred_draws() to get the distribution of the linear predictor.
For example, you used [add_]fitted_draws(..., scale = "response"), which
means you most likely want [add_]epred_draws(...).

quinn.brmsNB |> conditional_effects("SEASON:DENSITY") |> plot(points = TRUE)

quinn.brmsNB |> ggpredict(~SEASON+DENSITY) |> plot(add.data = TRUE)

quinn.brmsNB |> ggemmeans(~SEASON|DENSITY) |> plot(add.data = TRUE)

quinn.brmsNB |>
    fitted_draws(newdata=quinn) |>
    median_hdci() |>
    ggplot(aes(x=SEASON, colour=DENSITY, y=.value)) +
    geom_pointrange(aes(ymin=.lower, ymax=.upper), position = position_dodge(width=0.2)) + 
    geom_line(position = position_dodge(width=0.2)) +
    geom_point(data=quinn,  aes(y=RECRUITS,  x=SEASON, colour = DENSITY), position = position_dodge(width=0.2))
Warning: `fitted_draws` and `add_fitted_draws` are deprecated as their names were confusing.
Use [add_]epred_draws() to get the expectation of the posterior predictive.
Use [add_]linpred_draws() to get the distribution of the linear predictor.
For example, you used [add_]fitted_draws(..., scale = "response"), which
means you most likely want [add_]epred_draws(...).

10 Model investigation

The summary() method generates simple summaries (mean, standard deviation as well as 10, 50 and 90 percentiles).

quinn.rstanarmNB |> summary()

Model Info:
 function:     stan_glm
 family:       neg_binomial_2 [log]
 formula:      RECRUITS ~ SEASON * DENSITY
 algorithm:    sampling
 sample:       1800 (posterior sample size)
 priors:       see help('prior_summary')
 observations: 42
 predictors:   8

Estimates:
                          mean   sd   10%   50%   90%
(Intercept)              2.3    0.3  2.0   2.3   2.6 
SEASONSummer             1.6    0.3  1.2   1.6   2.0 
SEASONAutumn             0.7    0.3  0.2   0.7   1.1 
SEASONWinter            -0.6    0.4 -1.0  -0.6  -0.1 
DENSITYLow               0.1    0.4 -0.4   0.1   0.6 
SEASONSummer:DENSITYLow -0.9    0.5 -1.5  -0.9  -0.3 
SEASONAutumn:DENSITYLow -0.2    0.5 -0.9  -0.2   0.5 
SEASONWinter:DENSITYLow -0.9    0.7 -1.8  -0.9   0.0 
reciprocal_dispersion    4.0    1.3  2.5   3.8   5.7 

Fit Diagnostics:
           mean   sd   10%   50%   90%
mean_PPD 19.2    3.2 15.5  18.9  23.0 

The mean_ppd is the sample average posterior predictive distribution of the outcome variable (for details see help('summary.stanreg')).

MCMC diagnostics
                        mcse Rhat n_eff
(Intercept)             0.0  1.0  1606 
SEASONSummer            0.0  1.0  1681 
SEASONAutumn            0.0  1.0  1683 
SEASONWinter            0.0  1.0  1779 
DENSITYLow              0.0  1.0  1651 
SEASONSummer:DENSITYLow 0.0  1.0  1664 
SEASONAutumn:DENSITYLow 0.0  1.0  1684 
SEASONWinter:DENSITYLow 0.0  1.0  1820 
reciprocal_dispersion   0.0  1.0  1751 
mean_PPD                0.1  1.0  1643 
log-posterior           0.1  1.0  1657 

For each parameter, mcse is Monte Carlo standard error, n_eff is a crude measure of effective sample size, and Rhat is the potential scale reduction factor on split chains (at convergence Rhat=1).

Conclusions:

  • the intercept represents the estimated mean of the first combination of Season (Spring) and Density (High). On the link scale this is 2.31
  • the difference between Low and High adult density in spring is 1.58, although this is not significant
  • the difference between Spring and Summer for High adult density is 0.69
  • the difference between Spring and Autumn for High adult density is -0.57
  • the difference between Spring and Winter for High adult density is 0.12
  • if there were no interactions, we would expect the Low density Summer recruitment to be the additive of the main effects (Low and Summer). However, the modelled mean is 0.91 less than the additive effects would have expected. This value is significantly different to 0, indicating that there is evidence that the density effect in Summer is different to that in Spring.
  • the density effect in Autumn and Winter were not found to be significantly different from what you would expect from an additive model.
tidyMCMC(quinn.rstanarmNB$stanfit, estimate.method='median',  conf.int=TRUE,  conf.method='HPDinterval',  rhat=TRUE, ess=TRUE)
# A tibble: 11 × 7
   term                    estimate std.error  conf.low conf.high  rhat   ess
   <chr>                      <dbl>     <dbl>     <dbl>     <dbl> <dbl> <int>
 1 (Intercept)                2.31      0.251    1.84      2.79   1.00   1606
 2 SEASONSummer               1.58      0.339    0.913     2.25   1.00   1681
 3 SEASONAutumn               0.694     0.349    0.0468    1.41   0.999  1683
 4 SEASONWinter              -0.563     0.372   -1.25      0.175  1.00   1779
 5 DENSITYLow                 0.109     0.373   -0.571     0.871  1.00   1651
 6 SEASONSummer:DENSITYLow   -0.916     0.489   -1.84      0.0286 1.00   1664
 7 SEASONAutumn:DENSITYLow   -0.183     0.538   -1.23      0.814  0.999  1684
 8 SEASONWinter:DENSITYLow   -0.904     0.685   -2.22      0.402  0.999  1820
 9 reciprocal_dispersion      3.81      1.29     1.77      6.46   0.999  1751
10 mean_PPD                  18.9       3.17    13.8      25.4    1.00   1643
11 log-posterior           -155.        2.37  -160.     -151.     1.00   1657

Conclusions:

See above

quinn.rstanarmNB$stanfit |>
    summarise_draws(median,
                    HDInterval::hdi,
                    rhat, length, ess_bulk, ess_tail)
# A tibble: 11 × 8
   variable              median    lower    upper  rhat length ess_bulk ess_tail
   <chr>                  <num>    <num>    <num> <num>  <num>    <num>    <num>
 1 (Intercept)            2.31   1.84e+0  2.79e+0 1.00    1800    1619.    1460.
 2 SEASONSummer           1.58   9.13e-1  2.25e+0 1.00    1800    1689.    1672.
 3 SEASONAutumn           0.694  4.68e-2  1.41e+0 1.00    1800    1686.    1711.
 4 SEASONWinter          -0.563 -1.25e+0  1.75e-1 1.00    1800    1787.    1770.
 5 DENSITYLow             0.109 -5.71e-1  8.71e-1 1.00    1800    1665.    1830.
 6 SEASONSummer:DENSI…   -0.916 -1.84e+0  2.86e-2 1.00    1800    1671.    1769.
 7 SEASONAutumn:DENSI…   -0.183 -1.23e+0  8.14e-1 0.999   1800    1692.    1671.
 8 SEASONWinter:DENSI…   -0.904 -2.22e+0  4.02e-1 1.00    1800    1828.    1925.
 9 reciprocal_dispers…    3.81   1.77e+0  6.46e+0 1.00    1800    1689.    1744.
10 mean_PPD              18.9    1.38e+1  2.54e+1 1.00    1800    1708.    1644.
11 log-posterior       -155.    -1.60e+2 -1.51e+2 1.00    1800    1655.    1711.

We can also alter the CI level.

quinn.rstanarmNB$stanfit |>
    summarise_draws(median,
                    ~HDInterval::hdi(.x, credMass = 0.9),
                    rhat, length, ess_bulk, ess_tail)
# A tibble: 11 × 8
   variable              median    lower    upper  rhat length ess_bulk ess_tail
   <chr>                  <num>    <num>    <num> <num>  <num>    <num>    <num>
 1 (Intercept)            2.31   1.89e+0  2.69e+0 1.00    1800    1619.    1460.
 2 SEASONSummer           1.58   1.02e+0  2.13e+0 1.00    1800    1689.    1672.
 3 SEASONAutumn           0.694  9.45e-2  1.23e+0 1.00    1800    1686.    1711.
 4 SEASONWinter          -0.563 -1.16e+0  4.22e-2 1.00    1800    1787.    1770.
 5 DENSITYLow             0.109 -4.50e-1  7.69e-1 1.00    1800    1665.    1830.
 6 SEASONSummer:DENSI…   -0.916 -1.70e+0 -1.02e-1 1.00    1800    1671.    1769.
 7 SEASONAutumn:DENSI…   -0.183 -1.06e+0  6.73e-1 0.999   1800    1692.    1671.
 8 SEASONWinter:DENSI…   -0.904 -2.05e+0  1.40e-1 1.00    1800    1828.    1925.
 9 reciprocal_dispers…    3.81   1.87e+0  5.76e+0 1.00    1800    1689.    1744.
10 mean_PPD              18.9    1.41e+1  2.35e+1 1.00    1800    1708.    1644.
11 log-posterior       -155.    -1.59e+2 -1.52e+2 1.00    1800    1655.    1711.

Arguably, it would be better to back-transform to the ratio scale

quinn.rstanarmNB$stanfit |>
    summarise_draws(
        ~ median(exp(.x)),
        ~HDInterval::hdi(exp(.x)),
        rhat, length, ess_bulk, ess_tail)
# A tibble: 11 × 8
   variable  `~median(exp(.x))`    lower    upper  rhat length ess_bulk ess_tail
   <chr>                  <num>    <num>    <num> <num>  <num>    <num>    <num>
 1 (Interce…           1.01e+ 1 5.92e+ 0 1.56e+ 1 1.00    1800    1619.    1460.
 2 SEASONSu…           4.86e+ 0 2.17e+ 0 8.78e+ 0 1.00    1800    1689.    1672.
 3 SEASONAu…           2.00e+ 0 8.21e- 1 3.57e+ 0 1.00    1800    1686.    1711.
 4 SEASONWi…           5.70e- 1 2.36e- 1 1.06e+ 0 1.00    1800    1787.    1770.
 5 DENSITYL…           1.11e+ 0 4.52e- 1 2.14e+ 0 1.00    1800    1665.    1830.
 6 SEASONSu…           4.00e- 1 1.16e- 1 9.18e- 1 1.00    1800    1671.    1769.
 7 SEASONAu…           8.33e- 1 1.92e- 1 2.01e+ 0 0.999   1800    1692.    1671.
 8 SEASONWi…           4.05e- 1 4.95e- 2 1.25e+ 0 1.00    1800    1828.    1925.
 9 reciproc…           4.51e+ 1 3.19e+ 0 5.53e+ 2 1.00    1800    1689.    1744.
10 mean_PPD            1.62e+ 8 1.71e+ 5 4.26e+10 1.00    1800    1708.    1644.
11 log-post…           5.00e-68 1.81e-73 1.02e-66 1.00    1800    1655.    1711.
quinn.rstanarmNB$stanfit |> as_draws_df()
# A draws_df: 600 iterations, 3 chains, and 11 variables
   (Intercept) SEASONSummer SEASONAutumn SEASONWinter DENSITYLow
1          2.3         1.73        0.488       -0.675      0.471
2          2.6         0.98        0.375       -1.207      0.306
3          2.7         1.33        0.382       -0.945     -0.237
4          2.6         1.77        0.357       -0.231      0.031
5          2.3         1.44        0.747       -0.543      0.193
6          3.2         0.57       -0.188       -1.118     -0.749
7          2.2         1.60        0.279       -0.438      0.032
8          2.4         1.37        0.432        0.025     -0.161
9          2.7         1.00        0.091       -1.177     -0.804
10         2.6         1.26        0.340       -0.412     -0.367
   SEASONSummer:DENSITYLow SEASONAutumn:DENSITYLow SEASONWinter:DENSITYLow
1                   -1.404                   0.049                  -1.435
2                   -0.591                  -0.430                  -0.754
3                   -0.635                  -0.630                   0.260
4                   -1.580                  -0.144                  -2.152
5                   -1.062                  -0.493                  -0.524
6                   -0.116                   0.767                  -0.395
7                   -0.809                   0.789                   0.045
8                   -0.564                   0.442                   0.228
9                    0.188                   1.085                   1.759
10                  -0.046                   0.658                  -1.459
# ... with 1790 more draws, and 3 more variables
# ... hidden reserved variables {'.chain', '.iteration', '.draw'}
quinn.rstanarmNB$stanfit |>
    as_draws_df() |>
    summarise_draws(
        median,
        ~ HDInterval::hdi(.x),
        rhat,
        ess_bulk
    )
# A tibble: 11 × 6
   variable                  median     lower     upper  rhat ess_bulk
   <chr>                      <num>     <num>     <num> <num>    <num>
 1 (Intercept)                2.31     1.84      2.79   1.00     1619.
 2 SEASONSummer               1.58     0.913     2.25   1.00     1689.
 3 SEASONAutumn               0.694    0.0468    1.41   1.00     1686.
 4 SEASONWinter              -0.563   -1.25      0.175  1.00     1787.
 5 DENSITYLow                 0.109   -0.571     0.871  1.00     1665.
 6 SEASONSummer:DENSITYLow   -0.916   -1.84      0.0286 1.00     1671.
 7 SEASONAutumn:DENSITYLow   -0.183   -1.23      0.814  0.999    1692.
 8 SEASONWinter:DENSITYLow   -0.904   -2.22      0.402  1.00     1828.
 9 reciprocal_dispersion      3.81     1.77      6.46   1.00     1689.
10 mean_PPD                  18.9     13.8      25.4    1.00     1708.
11 log-posterior           -155.    -160.     -151.     1.00     1655.
quinn.rstanarmNB$stanfit |>
    as_draws_df() |>
    exp() |> 
    summarise_draws(
        median,
        ~ HDInterval::hdi(.x),
        rhat,
        ess_bulk
    )
# A tibble: 11 × 6
   variable                  median    lower    upper  rhat ess_bulk
   <chr>                      <num>    <num>    <num> <num>    <num>
 1 (Intercept)             1.01e+ 1 5.92e+ 0 1.56e+ 1 1.00     1619.
 2 SEASONSummer            4.86e+ 0 2.17e+ 0 8.78e+ 0 1.00     1689.
 3 SEASONAutumn            2.00e+ 0 8.21e- 1 3.57e+ 0 1.00     1686.
 4 SEASONWinter            5.70e- 1 2.36e- 1 1.06e+ 0 1.00     1787.
 5 DENSITYLow              1.11e+ 0 4.52e- 1 2.14e+ 0 1.00     1665.
 6 SEASONSummer:DENSITYLow 4.00e- 1 1.16e- 1 9.18e- 1 1.00     1671.
 7 SEASONAutumn:DENSITYLow 8.33e- 1 1.92e- 1 2.01e+ 0 0.999    1692.
 8 SEASONWinter:DENSITYLow 4.05e- 1 4.95e- 2 1.25e+ 0 1.00     1828.
 9 reciprocal_dispersion   4.51e+ 1 3.19e+ 0 5.53e+ 2 1.00     1689.
10 mean_PPD                1.62e+ 8 1.71e+ 5 4.26e+10 1.00     1708.
11 log-posterior           5.00e-68 1.81e-73 1.02e-66 1.00     1655.

Due to the presence of a log transform in the predictor, it is better to use the regex version.

quinn.rstanarmNB |> get_variables()
 [1] "(Intercept)"             "SEASONSummer"           
 [3] "SEASONAutumn"            "SEASONWinter"           
 [5] "DENSITYLow"              "SEASONSummer:DENSITYLow"
 [7] "SEASONAutumn:DENSITYLow" "SEASONWinter:DENSITYLow"
 [9] "reciprocal_dispersion"   "accept_stat__"          
[11] "stepsize__"              "treedepth__"            
[13] "n_leapfrog__"            "divergent__"            
[15] "energy__"               
quinn.draw <- quinn.rstanarmNB |> gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`,  regex=TRUE)
quinn.draw
# A tibble: 14,400 × 5
# Groups:   .variable [8]
   .chain .iteration .draw .variable   .value
    <int>      <int> <int> <chr>        <dbl>
 1      1          1     1 (Intercept)   2.34
 2      1          2     2 (Intercept)   2.60
 3      1          3     3 (Intercept)   2.72
 4      1          4     4 (Intercept)   2.62
 5      1          5     5 (Intercept)   2.31
 6      1          6     6 (Intercept)   3.23
 7      1          7     7 (Intercept)   2.24
 8      1          8     8 (Intercept)   2.36
 9      1          9     9 (Intercept)   2.72
10      1         10    10 (Intercept)   2.56
# ℹ 14,390 more rows
exceedP <- function(x, Val = 0) mean(x>Val)

quinn.rstanarmNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`,  regex=TRUE) |>
    mutate(.value = exp(.value)) |>
    summarise_draws(median,
                    HDInterval::hdi,
                    rhat,
                    length,
                    ess_bulk,
                    ess_tail,
                    ~ exceedP(.x, 1))
# A tibble: 8 × 10
# Groups:   .variable [8]
  .variable         variable median  lower  upper  rhat length ess_bulk ess_tail
  <chr>             <chr>     <dbl>  <dbl>  <dbl> <dbl>  <dbl>    <dbl>    <dbl>
1 (Intercept)       .value   10.1   5.92   15.6   1.00    1800    1619.    1460.
2 DENSITYLow        .value    1.11  0.452   2.14  1.00    1800    1665.    1830.
3 SEASONAutumn      .value    2.00  0.821   3.57  1.00    1800    1686.    1711.
4 SEASONAutumn:DEN… .value    0.833 0.192   2.01  0.999   1800    1692.    1671.
5 SEASONSummer      .value    4.86  2.17    8.78  1.00    1800    1689.    1672.
6 SEASONSummer:DEN… .value    0.400 0.116   0.918 1.00    1800    1671.    1769.
7 SEASONWinter      .value    0.570 0.236   1.06  1.00    1800    1787.    1770.
8 SEASONWinter:DEN… .value    0.405 0.0495  1.25  1.00    1800    1828.    1925.
# ℹ 1 more variable: `~exceedP(.x, 1)` <dbl>

We can then summarise this

quinn.draw |> median_hdci()
# A tibble: 8 × 7
  .variable               .value  .lower .upper .width .point .interval
  <chr>                    <dbl>   <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 (Intercept)              2.31   1.84   2.79     0.95 median hdci     
2 DENSITYLow               0.109 -0.571  0.871    0.95 median hdci     
3 SEASONAutumn             0.694  0.0468 1.41     0.95 median hdci     
4 SEASONAutumn:DENSITYLow -0.183 -1.23   0.814    0.95 median hdci     
5 SEASONSummer             1.58   0.913  2.25     0.95 median hdci     
6 SEASONSummer:DENSITYLow -0.916 -1.84   0.0286   0.95 median hdci     
7 SEASONWinter            -0.563 -1.25   0.175    0.95 median hdci     
8 SEASONWinter:DENSITYLow -0.904 -2.22   0.402    0.95 median hdci     

We could alternatively express the parameters on the response scale.

quinn.draw |> median_hdci(exp(.value))
# A tibble: 8 × 7
  .variable               `exp(.value)` .lower .upper .width .point .interval
  <chr>                           <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 (Intercept)                    10.1   5.92   15.6     0.95 median hdci     
2 DENSITYLow                      1.11  0.452   2.14    0.95 median hdci     
3 SEASONAutumn                    2.00  0.821   3.57    0.95 median hdci     
4 SEASONAutumn:DENSITYLow         0.833 0.192   2.01    0.95 median hdci     
5 SEASONSummer                    4.86  2.17    8.78    0.95 median hdci     
6 SEASONSummer:DENSITYLow         0.400 0.116   0.918   0.95 median hdci     
7 SEASONWinter                    0.570 0.236   1.06    0.95 median hdci     
8 SEASONWinter:DENSITYLow         0.405 0.0495  1.25    0.95 median hdci     
quinn.rstanarmNB |> 
  gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
  stat_halfeye(aes(x=.value,  y=.variable)) +
  facet_wrap(~.variable, scales='free')

quinn.rstanarmNB |> 
  gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
    geom_vline(xintercept=0, linetype='dashed') +
    stat_halfeye(aes(x=.value,  y=.variable)) +
    theme_classic()

We could alternatively express the parameters on the response scale.

quinn.rstanarmNB |> 
  gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
  group_by(.variable) |>
  mutate(.value=exp(.value)) |>
  median_hdci()
# A tibble: 8 × 7
  .variable               .value .lower .upper .width .point .interval
  <chr>                    <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 (Intercept)             10.1   5.92   15.6     0.95 median hdci     
2 DENSITYLow               1.11  0.452   2.14    0.95 median hdci     
3 SEASONAutumn             2.00  0.821   3.57    0.95 median hdci     
4 SEASONAutumn:DENSITYLow  0.833 0.192   2.01    0.95 median hdci     
5 SEASONSummer             4.86  2.17    8.78    0.95 median hdci     
6 SEASONSummer:DENSITYLow  0.400 0.116   0.918   0.95 median hdci     
7 SEASONWinter             0.570 0.236   1.06    0.95 median hdci     
8 SEASONWinter:DENSITYLow  0.405 0.0495  1.25    0.95 median hdci     
quinn.rstanarmNB |> 
  gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  mutate(.value=exp(.value)) |>
  ggplot() + 
    geom_vline(xintercept=1, linetype='dashed') +
    stat_halfeye(aes(x=.value,  y=.variable)) +
    scale_x_continuous('', trans = scales::log2_trans(), breaks=unique(as.vector(2^(0:4 %o% c(-1,1))))) +
    theme_classic()

quinn.rstanarmNB |> plot(plotfun='mcmc_intervals') 

## Link scale
quinn.rstanarmNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    ggplot() +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    geom_vline(xintercept=0, linetype='dashed') +
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) 
Warning: `stat(ggdist::cut_cdf_qi(cdf, .width = c(0.5, 0.8, 0.95), labels =
scales::percent_format()))` was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(ggdist::cut_cdf_qi(cdf, .width = c(0.5, 0.8, 0.95),
  labels = scales::percent_format()))` instead.

## Fractional scale
quinn.rstanarmNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    mutate(.value=exp(.value)) |>
    ggplot() +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    geom_vline(xintercept=1, linetype='dashed') +
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) +
    scale_x_continuous(trans = scales::log2_trans())

quinn.rstanarmNB |> 
  gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
  stat_halfeye(aes(x=.value,  y=.variable)) +
  facet_wrap(~.variable, scales='free')

quinn.rstanarmNB |> 
  gather_draws(`.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
    stat_halfeye(aes(x=.value,  y=.variable)) +
    geom_vline(xintercept = 0, linetype = 'dashed')

quinn.rstanarmNB |>  
  gather_draws(`.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
    stat_halfeye(aes(x=exp(.value),  y=.variable)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans())

quinn.rstanarmNB |> 
  gather_draws(`.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
    geom_density_ridges(aes(x=.value, y = .variable), alpha=0.4) +
    geom_vline(xintercept = 0, linetype = 'dashed')
Picking joint bandwidth of 0.0902

##Or on a fractional scale
quinn.rstanarmNB |> 
  gather_draws(`.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
    geom_density_ridges_gradient(aes(x=exp(.value),
                                     y = .variable,
                                     fill = stat(x)),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_c(option = "C")
Picking joint bandwidth of 0.13
Warning: Using the `size` aesthetic with geom_segment was deprecated in ggplot2 3.4.0.
ℹ Please use the `linewidth` aesthetic instead.

This is purely a graphical depiction on the posteriors.

quinn.rstanarmNB |> tidy_draws()
# A tibble: 1,800 × 18
   .chain .iteration .draw `(Intercept)` SEASONSummer SEASONAutumn SEASONWinter
    <int>      <int> <int>         <dbl>        <dbl>        <dbl>        <dbl>
 1      1          1     1          2.34        1.73        0.488       -0.675 
 2      1          2     2          2.60        0.981       0.375       -1.21  
 3      1          3     3          2.72        1.33        0.382       -0.945 
 4      1          4     4          2.62        1.77        0.357       -0.231 
 5      1          5     5          2.31        1.44        0.747       -0.543 
 6      1          6     6          3.23        0.575      -0.188       -1.12  
 7      1          7     7          2.24        1.60        0.279       -0.438 
 8      1          8     8          2.36        1.37        0.432        0.0251
 9      1          9     9          2.72        1.00        0.0913      -1.18  
10      1         10    10          2.56        1.26        0.340       -0.412 
# ℹ 1,790 more rows
# ℹ 11 more variables: DENSITYLow <dbl>, `SEASONSummer:DENSITYLow` <dbl>,
#   `SEASONAutumn:DENSITYLow` <dbl>, `SEASONWinter:DENSITYLow` <dbl>,
#   reciprocal_dispersion <dbl>, accept_stat__ <dbl>, stepsize__ <dbl>,
#   treedepth__ <dbl>, n_leapfrog__ <dbl>, divergent__ <dbl>, energy__ <dbl>
quinn.rstanarmNB |> spread_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`,  regex=TRUE)
# A tibble: 1,800 × 11
   .chain .iteration .draw `(Intercept)` SEASONSummer SEASONAutumn SEASONWinter
    <int>      <int> <int>         <dbl>        <dbl>        <dbl>        <dbl>
 1      1          1     1          2.34        1.73        0.488       -0.675 
 2      1          2     2          2.60        0.981       0.375       -1.21  
 3      1          3     3          2.72        1.33        0.382       -0.945 
 4      1          4     4          2.62        1.77        0.357       -0.231 
 5      1          5     5          2.31        1.44        0.747       -0.543 
 6      1          6     6          3.23        0.575      -0.188       -1.12  
 7      1          7     7          2.24        1.60        0.279       -0.438 
 8      1          8     8          2.36        1.37        0.432        0.0251
 9      1          9     9          2.72        1.00        0.0913      -1.18  
10      1         10    10          2.56        1.26        0.340       -0.412 
# ℹ 1,790 more rows
# ℹ 4 more variables: DENSITYLow <dbl>, `SEASONSummer:DENSITYLow` <dbl>,
#   `SEASONAutumn:DENSITYLow` <dbl>, `SEASONWinter:DENSITYLow` <dbl>
quinn.rstanarmNB |> posterior_samples() |> as_tibble()
Warning: Method 'posterior_samples' is deprecated. Please see ?as_draws for
recommended alternatives.
# A tibble: 1,800 × 9
   `(Intercept)` SEASONSummer SEASONAutumn SEASONWinter DENSITYLow
           <dbl>        <dbl>        <dbl>        <dbl>      <dbl>
 1          2.34        1.73        0.488       -0.675      0.471 
 2          2.60        0.981       0.375       -1.21       0.306 
 3          2.72        1.33        0.382       -0.945     -0.237 
 4          2.62        1.77        0.357       -0.231      0.0306
 5          2.31        1.44        0.747       -0.543      0.193 
 6          3.23        0.575      -0.188       -1.12      -0.749 
 7          2.24        1.60        0.279       -0.438      0.0317
 8          2.36        1.37        0.432        0.0251    -0.161 
 9          2.72        1.00        0.0913      -1.18      -0.804 
10          2.56        1.26        0.340       -0.412     -0.367 
# ℹ 1,790 more rows
# ℹ 4 more variables: `SEASONSummer:DENSITYLow` <dbl>,
#   `SEASONAutumn:DENSITYLow` <dbl>, `SEASONWinter:DENSITYLow` <dbl>,
#   reciprocal_dispersion <dbl>

Unfortunately, \(R^2\) calculations for models other than Gaussian and Binomial have not yet been implemented for rstanarm models yet.

#quinn.rstanarmNB |> bayes_R2() |> median_hdci

The summary() method generates simple summaries (mean, standard deviation as well as 10, 50 and 90 percentiles).

quinn.brmsNB |> summary()
 Family: negbinomial 
  Links: mu = log; shape = identity 
Formula: RECRUITS ~ SEASON * DENSITY 
   Data: quinn (Number of observations: 42) 
  Draws: 3 chains, each with iter = 5000; warmup = 2500; thin = 5;
         total post-warmup draws = 1500

Population-Level Effects: 
                        Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS
Intercept                   2.43      0.19     2.05     2.82 1.00     1660
SEASONSummer                1.39      0.26     0.90     1.88 1.00     1644
SEASONAutumn                0.54      0.26     0.02     1.05 1.00     1504
SEASONWinter               -0.70      0.30    -1.29    -0.10 1.00     1357
DENSITYLow                 -0.07      0.27    -0.60     0.48 1.00     1648
SEASONSummer:DENSITYLow    -0.63      0.36    -1.33     0.04 1.00     1535
SEASONAutumn:DENSITYLow     0.02      0.38    -0.69     0.78 1.00     1445
SEASONWinter:DENSITYLow    -0.62      0.50    -1.59     0.33 1.00     1567
                        Tail_ESS
Intercept                   1523
SEASONSummer                1582
SEASONAutumn                1498
SEASONWinter                1303
DENSITYLow                  1345
SEASONSummer:DENSITYLow     1417
SEASONAutumn:DENSITYLow     1460
SEASONWinter:DENSITYLow     1460

Family Specific Parameters: 
      Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
shape     6.69      3.05     2.88    14.60 1.00     1402     1459

Draws were sampled using sample(hmc). For each parameter, Bulk_ESS
and Tail_ESS are effective sample size measures, and Rhat is the potential
scale reduction factor on split chains (at convergence, Rhat = 1).

Conclusions:

  • the intercept represents the estimated mean of the first combination of Season (Spring) and Density (High). On the link scale this is 2.43
  • the difference between Low and High adult density in spring is 1.39, although this is not significant
  • the difference between Spring and Summer for High adult density is 0.54
  • the difference between Spring and Autumn for High adult density is -0.7
  • the difference between Spring and Winter for High adult density is -0.07
  • if there were no interactions, we would expect the Low density Summer recruitment to be the additive of the main effects (Low and Summer). However, the modelled mean is 0.63 less than the additive effects would have expected. This value is significantly different to 0, indicating that there is evidence that the density effect in Summer is different to that in Spring.
  • the density effect in Autumn and Winter were not found to be significantly different from what you would expect from an additive model.
quinn.brmsNB$fit |>
    tidyMCMC(estimate.method = 'median',
             conf.int = TRUE,
             conf.method = 'HPDinterval',
             rhat = TRUE,
             ess = TRUE)
# A tibble: 10 × 7
   term                      estimate std.error conf.low conf.high  rhat   ess
   <chr>                        <dbl>     <dbl>    <dbl>     <dbl> <dbl> <int>
 1 b_Intercept                 2.43       0.194   2.03      2.79   1.00   1649
 2 b_SEASONSummer              1.39       0.259   0.909     1.88   1.00   1645
 3 b_SEASONAutumn              0.541      0.260   0.0553    1.06   0.999  1504
 4 b_SEASONWinter             -0.699      0.298  -1.24     -0.0686 0.999  1339
 5 b_DENSITYLow               -0.0766     0.272  -0.576     0.488  1.00   1647
 6 b_SEASONSummer:DENSITYLow  -0.632      0.359  -1.33      0.0497 0.999  1527
 7 b_SEASONAutumn:DENSITYLow   0.0113     0.380  -0.757     0.715  0.998  1441
 8 b_SEASONWinter:DENSITYLow  -0.613      0.501  -1.60      0.311  0.999  1567
 9 shape                       6.09       3.05    2.41     12.9    1.00   1290
10 lprior                    -16.4        0.859 -18.2     -14.9    0.999  1680

Conclusions:

see above

quinn.brmsNB |> as_draws_df()
# A draws_df: 500 iterations, 3 chains, and 11 variables
   b_Intercept b_SEASONSummer b_SEASONAutumn b_SEASONWinter b_DENSITYLow
1          2.5            1.3           0.48          -0.83      -0.3414
2          2.6            1.5           0.85          -0.79      -0.6161
3          2.1            1.7           0.69          -0.30       0.1698
4          2.4            1.4           0.41          -0.66      -0.4238
5          2.5            1.3           0.26          -0.56      -0.2740
6          2.4            1.5           0.29          -0.72       0.0098
7          2.4            1.6           0.38          -0.26       0.3545
8          2.3            1.5           0.72          -0.56      -0.1369
9          2.5            1.4           0.29          -0.96      -0.1420
10         2.4            1.3           0.45          -0.54      -0.1729
   b_SEASONSummer:DENSITYLow b_SEASONAutumn:DENSITYLow
1                      -0.60                    0.5242
2                      -0.65                   -0.3431
3                      -1.14                   -0.0093
4                      -0.22                    0.8756
5                      -0.40                    0.3773
6                      -1.06                    0.6762
7                      -1.18                   -0.3360
8                      -0.60                    0.0343
9                      -0.59                    0.3559
10                     -0.34                    0.3772
   b_SEASONWinter:DENSITYLow
1                      -0.87
2                      -0.64
3                      -1.07
4                      -0.92
5                      -0.27
6                      -1.21
7                      -0.71
8                      -1.17
9                      -0.33
10                     -0.68
# ... with 1490 more draws, and 3 more variables
# ... hidden reserved variables {'.chain', '.iteration', '.draw'}
quinn.brmsNB |>
  as_draws_df() |>
  summarise_draws(
    median,
    ~ HDInterval::hdi(.x),
    rhat,
    ess_bulk, ess_tail
  )
# A tibble: 11 × 7
   variable                     median    lower    upper  rhat ess_bulk ess_tail
   <chr>                         <num>    <num>    <num> <num>    <num>    <num>
 1 b_Intercept                  2.43    2.03e+0  2.79e+0 1.00     1660.    1523.
 2 b_SEASONSummer               1.39    9.09e-1  1.88e+0 1.00     1644.    1582.
 3 b_SEASONAutumn               0.541   5.53e-2  1.06e+0 1.00     1504.    1498.
 4 b_SEASONWinter              -0.699  -1.24e+0 -6.86e-2 1.00     1357.    1303.
 5 b_DENSITYLow                -0.0766 -5.76e-1  4.88e-1 1.00     1647.    1345.
 6 b_SEASONSummer:DENSITYLow   -0.632  -1.33e+0  4.97e-2 1.00     1535.    1417.
 7 b_SEASONAutumn:DENSITYLow    0.0113 -7.57e-1  7.15e-1 1.00     1446.    1460.
 8 b_SEASONWinter:DENSITYLow   -0.613  -1.60e+0  3.11e-1 1.00     1567.    1460.
 9 shape                        6.09    2.41e+0  1.29e+1 1.00     1402.    1459.
10 lprior                     -16.4    -1.82e+1 -1.49e+1 0.999    1691.    1321.
11 lp__                      -157.     -1.62e+2 -1.53e+2 1.00     1418.    1421.
quinn.brmsNB |>
    as_draws_df() |>
    exp() |>
    summarise_draws(
        median,
        HDInterval::hdi,
        rhat,
        length,
        ess_bulk, ess_tail
    )
# A tibble: 11 × 8
   variable              median    lower    upper  rhat length ess_bulk ess_tail
   <chr>                  <num>    <num>    <num> <num>  <num>    <num>    <num>
 1 b_Intercept         1.13e+ 1 7.64e+ 0 1.62e+ 1 1.00    1500    1660.    1523.
 2 b_SEASONSummer      4.03e+ 0 2.41e+ 0 6.43e+ 0 1.00    1500    1644.    1582.
 3 b_SEASONAutumn      1.72e+ 0 9.39e- 1 2.71e+ 0 1.00    1500    1504.    1498.
 4 b_SEASONWinter      4.97e- 1 2.41e- 1 8.23e- 1 1.00    1500    1357.    1303.
 5 b_DENSITYLow        9.26e- 1 4.80e- 1 1.49e+ 0 1.00    1500    1647.    1345.
 6 b_SEASONSummer:DEN… 5.31e- 1 2.43e- 1 9.97e- 1 1.00    1500    1535.    1417.
 7 b_SEASONAutumn:DEN… 1.01e+ 0 4.45e- 1 2.01e+ 0 1.00    1500    1446.    1460.
 8 b_SEASONWinter:DEN… 5.42e- 1 1.54e- 1 1.25e+ 0 0.999   1500    1567.    1460.
 9 shape               4.41e+ 2 5.06e+ 0 2.92e+ 5 1.00    1500    1402.    1459.
10 lprior              7.80e- 8 3.68e- 9 2.52e- 7 0.999   1500    1691.    1321.
11 lp__                6.88e-69 6.20e-75 1.27e-67 1.00    1500    1418.    1421.

Due to the presence of a log transform in the predictor, it is better to use the regex version.

quinn.brmsNB |> get_variables()
 [1] "b_Intercept"               "b_SEASONSummer"           
 [3] "b_SEASONAutumn"            "b_SEASONWinter"           
 [5] "b_DENSITYLow"              "b_SEASONSummer:DENSITYLow"
 [7] "b_SEASONAutumn:DENSITYLow" "b_SEASONWinter:DENSITYLow"
 [9] "shape"                     "lprior"                   
[11] "lp__"                      "accept_stat__"            
[13] "treedepth__"               "stepsize__"               
[15] "divergent__"               "n_leapfrog__"             
[17] "energy__"                 
quinn.draw <- quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`,  regex = TRUE)
quinn.draw
# A tibble: 10,500 × 5
# Groups:   .variable [7]
   .chain .iteration .draw .variable      .value
    <int>      <int> <int> <chr>           <dbl>
 1      1          1     1 b_SEASONSummer   1.33
 2      1          2     2 b_SEASONSummer   1.52
 3      1          3     3 b_SEASONSummer   1.70
 4      1          4     4 b_SEASONSummer   1.40
 5      1          5     5 b_SEASONSummer   1.31
 6      1          6     6 b_SEASONSummer   1.55
 7      1          7     7 b_SEASONSummer   1.62
 8      1          8     8 b_SEASONSummer   1.51
 9      1          9     9 b_SEASONSummer   1.36
10      1         10    10 b_SEASONSummer   1.26
# ℹ 10,490 more rows
quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`,  regex = TRUE) |>
    mutate(.value = exp(.value)) |>
    summarise_draws(median,
                    ~HDInterval::hdi(.x, credMass = 0.95),
                    rhat,
                    length,
                    ess_bulk, ess_tail)
# A tibble: 7 × 9
# Groups:   .variable [7]
  .variable           variable median lower upper  rhat length ess_bulk ess_tail
  <chr>               <chr>     <dbl> <dbl> <dbl> <dbl>  <dbl>    <dbl>    <dbl>
1 b_DENSITYLow        .value    0.926 0.480 1.49  1.00    1500    1647.    1345.
2 b_SEASONAutumn      .value    1.72  0.939 2.71  1.00    1500    1504.    1498.
3 b_SEASONAutumn:DEN… .value    1.01  0.445 2.01  1.00    1500    1446.    1460.
4 b_SEASONSummer      .value    4.03  2.41  6.43  1.00    1500    1644.    1582.
5 b_SEASONSummer:DEN… .value    0.531 0.243 0.997 1.00    1500    1535.    1417.
6 b_SEASONWinter      .value    0.497 0.241 0.823 1.00    1500    1357.    1303.
7 b_SEASONWinter:DEN… .value    0.542 0.154 1.25  0.999   1500    1567.    1460.
exceedP <- function(x, Val = 0) mean(x>Val)
quinn.brmsNB |>
    tidy_draws() |>
    exp() |>
    dplyr::select(starts_with("b_")) |>
    summarise_draws(median,
                    ~HDInterval::hdi(.x, credMass = 0.9),
                    rhat,
                    ess_bulk, ess_tail,
                    ~exceedP(.x, 1))
# A tibble: 8 × 8
  variable         median lower  upper  rhat ess_bulk ess_tail `~exceedP(.x, 1)`
  <chr>             <num> <num>  <num> <num>    <num>    <num>             <num>
1 b_Intercept      11.3   8.06  15.1   1.00     1659.    1520.            1     
2 b_SEASONSummer    4.03  2.49   5.84  0.999    1645.    1569.            1     
3 b_SEASONAutumn    1.72  1.01   2.47  1.00     1500.    1489.            0.979 
4 b_SEASONWinter    0.497 0.294  0.774 0.999    1300.    1264.            0.0107
5 b_DENSITYLow      0.926 0.539  1.36  1.00     1643.    1330.            0.407 
6 b_SEASONSummer:…  0.531 0.266  0.886 1.00     1531.    1380.            0.0373
7 b_SEASONAutumn:…  1.01  0.451  1.71  0.999    1439.    1452.            0.513 
8 b_SEASONWinter:…  0.542 0.186  1.07  1.00     1559.    1394.            0.109 

We can then summarise this

quinn.draw |> median_hdci()
# A tibble: 7 × 7
  .variable                  .value  .lower  .upper .width .point .interval
  <chr>                       <dbl>   <dbl>   <dbl>  <dbl> <chr>  <chr>    
1 b_DENSITYLow              -0.0766 -0.576   0.488    0.95 median hdci     
2 b_SEASONAutumn             0.541   0.0553  1.06     0.95 median hdci     
3 b_SEASONAutumn:DENSITYLow  0.0113 -0.757   0.715    0.95 median hdci     
4 b_SEASONSummer             1.39    0.909   1.88     0.95 median hdci     
5 b_SEASONSummer:DENSITYLow -0.632  -1.33    0.0497   0.95 median hdci     
6 b_SEASONWinter            -0.699  -1.24   -0.0686   0.95 median hdci     
7 b_SEASONWinter:DENSITYLow -0.613  -1.60    0.311    0.95 median hdci     

We could alternatively express the parameters on the response scale.

quinn.draw |> 
  median_hdci(exp(.value))
# A tibble: 7 × 7
  .variable                 `exp(.value)` .lower .upper .width .point .interval
  <chr>                             <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 b_DENSITYLow                      0.926  0.480  1.49    0.95 median hdci     
2 b_SEASONAutumn                    1.72   0.939  2.71    0.95 median hdci     
3 b_SEASONAutumn:DENSITYLow         1.01   0.445  2.01    0.95 median hdci     
4 b_SEASONSummer                    4.03   2.41   6.43    0.95 median hdci     
5 b_SEASONSummer:DENSITYLow         0.531  0.243  0.997   0.95 median hdci     
6 b_SEASONWinter                    0.497  0.241  0.823   0.95 median hdci     
7 b_SEASONWinter:DENSITYLow         0.542  0.154  1.25    0.95 median hdci     
quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
    ggplot() +
    geom_vline(xintercept=0, linetype='dashed') +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) 
Warning: `stat(ggdist::cut_cdf_qi(cdf, .width = c(0.5, 0.8, 0.95), labels =
scales::percent_format()))` was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(ggdist::cut_cdf_qi(cdf, .width = c(0.5, 0.8, 0.95),
  labels = scales::percent_format()))` instead.

quinn.brmsNB |> 
  gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |> 
  ggplot() + 
    geom_vline(xintercept=0, linetype='dashed') +
    stat_halfeye(aes(x=.value,  y=.variable)) +
    theme_classic()

We could alternatively express the parameters on the response scale.

quinn.brmsNB |> 
  gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
  group_by(.variable) |>
  mutate(.value=exp(.value)) |>
  median_hdci()
# A tibble: 7 × 7
  .variable                 .value .lower .upper .width .point .interval
  <chr>                      <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 b_DENSITYLow               0.926  0.480  1.49    0.95 median hdci     
2 b_SEASONAutumn             1.72   0.939  2.71    0.95 median hdci     
3 b_SEASONAutumn:DENSITYLow  1.01   0.445  2.01    0.95 median hdci     
4 b_SEASONSummer             4.03   2.41   6.43    0.95 median hdci     
5 b_SEASONSummer:DENSITYLow  0.531  0.243  0.997   0.95 median hdci     
6 b_SEASONWinter             0.497  0.241  0.823   0.95 median hdci     
7 b_SEASONWinter:DENSITYLow  0.542  0.154  1.25    0.95 median hdci     
quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    mutate(.value=exp(.value)) |>
    ggplot() +
    geom_vline(xintercept=1, linetype='dashed') +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    scale_x_continuous('', trans = scales::log2_trans(), breaks=unique(as.vector(2^(0:4 %o% c(-1,1))))) +
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) +
    theme_classic()
Warning: `stat(ggdist::cut_cdf_qi(cdf, .width = c(0.5, 0.8, 0.95), labels =
scales::percent_format()))` was deprecated in ggplot2 3.4.0.
ℹ Please use `after_stat(ggdist::cut_cdf_qi(cdf, .width = c(0.5, 0.8, 0.95),
  labels = scales::percent_format()))` instead.

Conclusions:

  • the estimated mean (expected number of newly recruited barnacles) on the ALG1 surface is -0.08. This is the mean of the posterior distribution for this parameter. If we back-transform this to the response scale, this becomes 0.93.
  • the estimated effect of ALG2 vs ALG1 is 0.54 (median) with a standard error of 0.06. The 95% credibility intervals indicate that we are 95% confident that the effect is between 1.06 and 0.95 - e.g. there is a significant positive effect. When back-transformed onto the response scale, we see that barnacle recruitment on ALG2 is 1.72 times higher than that on ALG1. This represents a 72% increase in barnacle recruitment.
  • the estimated effect of NB and S are 0.01 and 1.39 respectively, which equate to 0.99 and 0.25 fold declines respectively.
  • Rhat and number of effective samples for each parameter are also provided as MCMC diagnostics and all look good.
quinn.brmsNB$fit |> plot(type='intervals') 
ci_level: 0.8 (80% intervals)
outer_level: 0.95 (95% intervals)

## Link scale
quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    ggplot() +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    geom_vline(xintercept=0, linetype='dashed') +
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) 

## Fractional scale
quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    mutate(.value=exp(.value)) |>
    ggplot() +
    stat_slab(aes(x = .value, y = .variable,
                  fill = stat(ggdist::cut_cdf_qi(cdf,
                           .width = c(0.5, 0.8, 0.95), 
                           labels = scales::percent_format())
                           )), color='black') + 
    geom_vline(xintercept=1, linetype='dashed') +
    scale_fill_brewer('Interval', direction = -1, na.translate = FALSE) +
    scale_x_continuous(trans = scales::log2_trans())

quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    ggplot() + 
    stat_halfeye(aes(x=.value,  y=.variable)) +
    facet_wrap(~.variable, scales='free')

quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    ggplot() + 
    stat_halfeye(aes(x=.value,  y=.variable)) +
    geom_vline(xintercept = 0, linetype = 'dashed')

quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    ggplot() + 
    stat_halfeye(aes(x=exp(.value),  y=.variable)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans())

quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    ggplot() + 
    geom_density_ridges(aes(x=.value, y = .variable), alpha=0.4) +
    geom_vline(xintercept = 0, linetype = 'dashed')
Picking joint bandwidth of 0.0693

##Or on a fractional scale
quinn.brmsNB |>
    gather_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`, regex=TRUE) |>
    ggplot() + 
    geom_density_ridges_gradient(aes(x=exp(.value),
                                     y = .variable,
                                     fill = stat(x)),
                                 alpha=0.4, colour = 'white',
                                 quantile_lines = TRUE,
                                 quantiles = c(0.025, 0.975)) +
    geom_vline(xintercept = 1, linetype = 'dashed') +
    scale_x_continuous(trans = scales::log2_trans()) +
    scale_fill_viridis_c(option = "C")
Picking joint bandwidth of 0.1
Warning: Using the `size` aesthetic with geom_segment was deprecated in ggplot2 3.4.0.
ℹ Please use the `linewidth` aesthetic instead.

This is purely a graphical depiction on the posteriors.

quinn.brmsNB |> tidy_draws()
# A tibble: 1,500 × 20
   .chain .iteration .draw b_Intercept b_SEASONSummer b_SEASONAutumn
    <int>      <int> <int>       <dbl>          <dbl>          <dbl>
 1      1          1     1        2.50           1.33          0.478
 2      1          2     2        2.57           1.52          0.852
 3      1          3     3        2.14           1.70          0.688
 4      1          4     4        2.44           1.40          0.415
 5      1          5     5        2.52           1.31          0.257
 6      1          6     6        2.36           1.55          0.287
 7      1          7     7        2.36           1.62          0.380
 8      1          8     8        2.29           1.51          0.717
 9      1          9     9        2.49           1.36          0.292
10      1         10    10        2.43           1.26          0.453
# ℹ 1,490 more rows
# ℹ 14 more variables: b_SEASONWinter <dbl>, b_DENSITYLow <dbl>,
#   `b_SEASONSummer:DENSITYLow` <dbl>, `b_SEASONAutumn:DENSITYLow` <dbl>,
#   `b_SEASONWinter:DENSITYLow` <dbl>, shape <dbl>, lprior <dbl>, lp__ <dbl>,
#   accept_stat__ <dbl>, treedepth__ <dbl>, stepsize__ <dbl>,
#   divergent__ <dbl>, n_leapfrog__ <dbl>, energy__ <dbl>
quinn.brmsNB |> spread_draws(`.Intercept.*|.*SEASON.*|.*DENSITY.*`,  regex=TRUE)
# A tibble: 1,500 × 10
   .chain .iteration .draw b_SEASONSummer b_SEASONAutumn b_SEASONWinter
    <int>      <int> <int>          <dbl>          <dbl>          <dbl>
 1      1          1     1           1.33          0.478         -0.829
 2      1          2     2           1.52          0.852         -0.786
 3      1          3     3           1.70          0.688         -0.300
 4      1          4     4           1.40          0.415         -0.658
 5      1          5     5           1.31          0.257         -0.564
 6      1          6     6           1.55          0.287         -0.723
 7      1          7     7           1.62          0.380         -0.260
 8      1          8     8           1.51          0.717         -0.563
 9      1          9     9           1.36          0.292         -0.965
10      1         10    10           1.26          0.453         -0.540
# ℹ 1,490 more rows
# ℹ 4 more variables: b_DENSITYLow <dbl>, `b_SEASONSummer:DENSITYLow` <dbl>,
#   `b_SEASONAutumn:DENSITYLow` <dbl>, `b_SEASONWinter:DENSITYLow` <dbl>
quinn.brmsNB |> posterior_samples() |> as_tibble()
Warning: Method 'posterior_samples' is deprecated. Please see ?as_draws for
recommended alternatives.
# A tibble: 1,500 × 11
   b_Intercept b_SEASONSummer b_SEASONAutumn b_SEASONWinter b_DENSITYLow
         <dbl>          <dbl>          <dbl>          <dbl>        <dbl>
 1        2.50           1.33          0.478         -0.829     -0.341  
 2        2.57           1.52          0.852         -0.786     -0.616  
 3        2.14           1.70          0.688         -0.300      0.170  
 4        2.44           1.40          0.415         -0.658     -0.424  
 5        2.52           1.31          0.257         -0.564     -0.274  
 6        2.36           1.55          0.287         -0.723      0.00979
 7        2.36           1.62          0.380         -0.260      0.355  
 8        2.29           1.51          0.717         -0.563     -0.137  
 9        2.49           1.36          0.292         -0.965     -0.142  
10        2.43           1.26          0.453         -0.540     -0.173  
# ℹ 1,490 more rows
# ℹ 6 more variables: `b_SEASONSummer:DENSITYLow` <dbl>,
#   `b_SEASONAutumn:DENSITYLow` <dbl>, `b_SEASONWinter:DENSITYLow` <dbl>,
#   shape <dbl>, lprior <dbl>, lp__ <dbl>
quinn.brmsNB |> bayes_R2(summary=FALSE) |> median_hdci()
          y      ymin      ymax .width .point .interval
1 0.7229585 0.5152732 0.8080371   0.95 median      hdci

Region of Practical Equivalence

0.1 * log(sd(quinn$RECRUITS))
[1] 0.2754809
quinn.brmsNB |> rope(range = c(-0.28, 0.28))
Possible multicollinearity between b_SEASONSummer:DENSITYLow and b_DENSITYLow (r = 0.72). This might lead to inappropriate results. See 'Details' in '?rope'.
# Proportion of samples inside the ROPE [-0.28, 0.28]:

Parameter               | inside ROPE
-------------------------------------
Intercept               |      0.00 %
SEASONSummer            |      0.00 %
SEASONAutumn            |     14.26 %
SEASONWinter            |      5.83 %
DENSITYLow              |     71.70 %
SEASONSummer:DENSITYLow |     14.75 %
SEASONAutumn:DENSITYLow |     57.23 %
SEASONWinter:DENSITYLow |     21.91 %
rope(quinn.brmsNB, range = c(-0.28, 0.28)) |> plot()
Possible multicollinearity between b_SEASONSummer:DENSITYLow and b_DENSITYLow (r = 0.72). This might lead to inappropriate results. See 'Details' in '?rope'.

## Or based on fractional scale
quinn.brmsNB |>
    as_draws_df('^b_SEASON.*|^b_DENSITY.*', regex = TRUE) |>
    exp() |> 
    ## equivalence_test(range = c(0.755, 1.32))
    rope(range = c(0.755, 1.32))
# Proportion of samples inside the ROPE [0.76, 1.32]:

Parameter               | inside ROPE
-------------------------------------
SEASONSummer            |      0.00 %
SEASONAutumn            |     14.19 %
SEASONWinter            |      5.90 %
DENSITYLow              |     71.63 %
SEASONSummer:DENSITYLow |     14.89 %
SEASONAutumn:DENSITYLow |     56.95 %
SEASONWinter:DENSITYLow |     21.91 %
quinn.mcmc <-
    quinn.brmsNB |>
    as_draws_df('^b_SEASON.*|^b_DENSITY.*', regex = TRUE) |>
    exp()
quinn.mcmc |>
    rope(range = c(0.755, 1.32))
# Proportion of samples inside the ROPE [0.76, 1.32]:

Parameter               | inside ROPE
-------------------------------------
SEASONSummer            |      0.00 %
SEASONAutumn            |     14.19 %
SEASONWinter            |      5.90 %
DENSITYLow              |     71.63 %
SEASONSummer:DENSITYLow |     14.89 %
SEASONAutumn:DENSITYLow |     56.95 %
SEASONWinter:DENSITYLow |     21.91 %
## note, the following is not quit correct, it does not get the CI correct
quinn.mcmc |>
    rope(range = c(0.755, 1.32)) |>
    plot(data = quinn.brmsNB)

quinn.mcmc |>
    equivalence_test(range = c(0.755, 1.32)) 
# Test for Practical Equivalence

  ROPE: [0.76 1.32]

Parameter               |        H0 | inside ROPE |     95% HDI
---------------------------------------------------------------
SEASONSummer            |  Rejected |      0.00 % | [2.46 6.52]
SEASONAutumn            | Undecided |     14.19 % | [1.02 2.85]
SEASONWinter            | Undecided |      5.90 % | [0.27 0.91]
DENSITYLow              | Undecided |     71.63 % | [0.55 1.61]
SEASONSummer:DENSITYLow | Undecided |     14.89 % | [0.26 1.05]
SEASONAutumn:DENSITYLow | Undecided |     56.95 % | [0.50 2.19]
SEASONWinter:DENSITYLow | Undecided |     21.91 % | [0.20 1.39]

11 Further investigations

## fold scale
quinn.rstanarmNB |>
    emmeans(~DENSITY|SEASON, type='response') |>
    pairs()
Warning: Model has 0 prior weights, but we recovered 42 rows of data.
So prior weights were ignored.
SEASON = Spring:
 contrast   ratio lower.HPD upper.HPD
 High / Low 0.897     0.375      1.65

SEASON = Summer:
 contrast   ratio lower.HPD upper.HPD
 High / Low 2.190     0.985      3.76

SEASON = Autumn:
 contrast   ratio lower.HPD upper.HPD
 High / Low 1.069     0.409      2.02

SEASON = Winter:
 contrast   ratio lower.HPD upper.HPD
 High / Low 2.200     0.368      5.48

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
## absolute response scale
quinn.rstanarmNB |>
    emmeans(~DENSITY|SEASON, type='link') |>
    regrid() |>
    pairs()
Warning: Model has 0 prior weights, but we recovered 42 rows of data.
So prior weights were ignored.
SEASON = Spring:
 contrast   estimate lower.HPD upper.HPD
 High - Low    -1.16    -10.54      6.33

SEASON = Summer:
 contrast   estimate lower.HPD upper.HPD
 High - Low    26.25      2.72     53.08

SEASON = Autumn:
 contrast   estimate lower.HPD upper.HPD
 High - Low     1.22    -17.13     15.26

SEASON = Winter:
 contrast   estimate lower.HPD upper.HPD
 High - Low     3.04     -1.32      7.75

Point estimate displayed: median 
HPD interval probability: 0.95 
quinn.em <- quinn.rstanarmNB |>
    emmeans(~DENSITY|SEASON, type='link') |>
    pairs() |>
    gather_emmeans_draws() |> 
    mutate(Fit=exp(.value))
Warning: Model has 0 prior weights, but we recovered 42 rows of data.
So prior weights were ignored.
head(quinn.em)
# A tibble: 6 × 7
# Groups:   contrast, SEASON [1]
  contrast   SEASON .chain .iteration .draw  .value   Fit
  <fct>      <fct>   <int>      <int> <int>   <dbl> <dbl>
1 High - Low Spring     NA         NA     1 -0.471  0.625
2 High - Low Spring     NA         NA     2 -0.306  0.736
3 High - Low Spring     NA         NA     3  0.237  1.27 
4 High - Low Spring     NA         NA     4 -0.0306 0.970
5 High - Low Spring     NA         NA     5 -0.193  0.824
6 High - Low Spring     NA         NA     6  0.749  2.11 
g2 <- quinn.em |>
  group_by(contrast, SEASON) |>
  median_hdci() |>
  ggplot() +
  geom_vline(xintercept=1, linetype='dashed') +
  geom_pointrange(aes(x=Fit, y=SEASON, xmin=Fit.lower, xmax=Fit.upper)) + 
  scale_x_continuous('Effect size (High/Low)', trans = scales::log2_trans(), breaks=unique(as.vector(2^(0:4 %o% c(-1,1))))) +
  theme_classic()
g2

ggplot(quinn.em, aes(x=Fit)) +
    geom_histogram() +
    geom_vline(xintercept = 1, linetype='dashed') +
    scale_x_continuous('Effect size (High/Low)', trans = scales::log2_trans(), breaks=unique(as.vector(2^(0:4 %o% c(-1,1))))) +
    facet_wrap(SEASON~contrast, scales='free')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

quinn.em |> group_by(contrast, SEASON) |> median_hdci(Fit)
# A tibble: 4 × 8
  contrast   SEASON   Fit .lower .upper .width .point .interval
  <fct>      <fct>  <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 High - Low Spring 0.897  0.375   1.65   0.95 median hdci     
2 High - Low Summer 2.19   0.985   3.76   0.95 median hdci     
3 High - Low Autumn 1.07   0.409   2.02   0.95 median hdci     
4 High - Low Winter 2.20   0.368   5.48   0.95 median hdci     
# Probability of effect
quinn.em |> group_by(contrast,SEASON) |> summarize(P=mean(Fit>1))
`summarise()` has grouped output by 'contrast'. You can override using the
`.groups` argument.
# A tibble: 4 × 3
# Groups:   contrast [1]
  contrast   SEASON     P
  <fct>      <fct>  <dbl>
1 High - Low Spring 0.378
2 High - Low Summer 0.992
3 High - Low Autumn 0.572
4 High - Low Winter 0.915
##Probability of effect greater than 10%
quinn.em |> group_by(contrast,SEASON) |> summarize(P=mean(Fit>1.1))
`summarise()` has grouped output by 'contrast'. You can override using the
`.groups` argument.
# A tibble: 4 × 3
# Groups:   contrast [1]
  contrast   SEASON     P
  <fct>      <fct>  <dbl>
1 High - Low Spring 0.288
2 High - Low Summer 0.982
3 High - Low Autumn 0.469
4 High - Low Winter 0.884
## Using summarise_draws
quinn.rstanarmNB |>
    emmeans(~DENSITY|SEASON, type='link') |>
    pairs() |>
    tidy_draws() |>
    exp() |>
    summarise_draws(median,
                    HDInterval::hdi,
                    P = ~ mean(.x > 1)
                    )
Warning: Model has 0 prior weights, but we recovered 42 rows of data.
So prior weights were ignored.
# A tibble: 4 × 5
  variable                          median lower upper     P
  <chr>                              <num> <num> <num> <num>
1 contrast High - Low SEASON Spring  0.897 0.375  1.65 0.378
2 contrast High - Low SEASON Summer  2.19  0.985  3.76 0.992
3 contrast High - Low SEASON Autumn  1.07  0.409  2.02 0.572
4 contrast High - Low SEASON Winter  2.20  0.368  5.48 0.915
newdata <- with(quinn, expand.grid(SEASON = levels(SEASON),
                                  DENSITY = levels(DENSITY)))
Xmat<- model.matrix(~SEASON*DENSITY, data = newdata)
as.matrix(quinn.rstanarmNB) |> head()
          parameters
iterations (Intercept) SEASONSummer SEASONAutumn SEASONWinter  DENSITYLow
      [1,]    2.342131    1.7293124    0.4876410   -0.6746084  0.47062928
      [2,]    2.604653    0.9814157    0.3748547   -1.2071068  0.30621406
      [3,]    2.722089    1.3322493    0.3819772   -0.9452799 -0.23695767
      [4,]    2.616795    1.7698216    0.3570658   -0.2313055  0.03061853
      [5,]    2.306493    1.4441744    0.7466527   -0.5430116  0.19332763
      [6,]    3.226903    0.5749714   -0.1876490   -1.1179834 -0.74899846
          parameters
iterations SEASONSummer:DENSITYLow SEASONAutumn:DENSITYLow
      [1,]              -1.4044154              0.04924349
      [2,]              -0.5908813             -0.43043862
      [3,]              -0.6350192             -0.63019880
      [4,]              -1.5801371             -0.14430468
      [5,]              -1.0616049             -0.49322455
      [6,]              -0.1164619              0.76720964
          parameters
iterations SEASONWinter:DENSITYLow reciprocal_dispersion
      [1,]              -1.4349051              4.309429
      [2,]              -0.7539208              3.468780
      [3,]               0.2600093              2.219612
      [4,]              -2.1516281              2.757175
      [5,]              -0.5244181              5.892901
      [6,]              -0.3951004              3.234728
## coefs <- as.matrix(quinn.rstanarmNB)
coefs <- as.matrix(as.data.frame(quinn.rstanarmNB) |>
                  dplyr:::select(-reciprocal_dispersion)) |>
    as.matrix()
fit <- exp(coefs %*% t(Xmat))
newdata <- newdata |>
    cbind(tidyMCMC(fit, conf.int = TRUE, conf.method = 'HPDinterval'))
head(newdata)
  SEASON DENSITY term  estimate std.error  conf.low conf.high
1 Spring    High    1 10.055043  2.735607  5.915025 15.611565
2 Summer    High    2 48.795287 12.011632 29.545096 73.583424
3 Autumn    High    3 20.087783  5.079601 11.915208 30.532792
4 Winter    High    4  5.739096  1.686771  2.883103  9.249068
5 Spring     Low    5 11.330085  3.355549  6.349998 18.806613
6 Summer     Low    6 22.186561  5.608697 13.120594 33.300954
ggplot(newdata, aes(y = estimate, x = SEASON, fill = DENSITY)) +
    geom_blank() +
    geom_line(aes(x=as.numeric(SEASON), ymin=conf.low, ymax=conf.high, linetype=DENSITY),
              position = position_dodge(0.2))+
    geom_pointrange(aes(ymin=conf.low, ymax=conf.high), shape=21,
                    position = position_dodge(0.2)) 
Warning in geom_line(aes(x = as.numeric(SEASON), ymin = conf.low, ymax =
conf.high, : Ignoring unknown aesthetics: ymin and ymax

#Compare high and low in each season
#via contrasts
newdata <- with(quinn, expand.grid(SEASON = levels(SEASON),
                                   DENSITY = levels(DENSITY)))
## factor differences
Xmat<- model.matrix(~SEASON*DENSITY, data=newdata)
Xmat.high <- Xmat[newdata$DENSITY=="High",]
Xmat.low <- Xmat[newdata$DENSITY=="Low",]
Xmat.density <- Xmat.high-Xmat.low
rownames(Xmat.density) <- levels(quinn$SEASON)
coefs = as.matrix(as.data.frame(quinn.rstanarmNB) |> dplyr:::select(-reciprocal_dispersion))
fit = exp(coefs %*% t(Xmat.density))
tidyMCMC(fit, conf.int=TRUE, conf.method='HPDinterval')
# A tibble: 4 × 5
  term   estimate std.error conf.low conf.high
  <chr>     <dbl>     <dbl>    <dbl>     <dbl>
1 Spring    0.897     0.367    0.375      1.65
2 Summer    2.19      0.777    0.985      3.76
3 Autumn    1.07      0.454    0.409      2.02
4 Winter    2.20      1.65     0.368      5.48
## or absolute
fit.high = coefs %*% t(Xmat.high)
fit.low = coefs %*% t(Xmat.low)
fit = exp(fit.high) - exp(fit.low)
#fit = exp(fit.high - fit.low)
tidyMCMC(fit, conf.int=TRUE, conf.method='HPDinterval')
# A tibble: 4 × 5
  term  estimate std.error conf.low conf.high
  <chr>    <dbl>     <dbl>    <dbl>     <dbl>
1 1        -1.16      4.33   -10.5       6.33
2 2        26.3      13.3      2.72     53.1 
3 3         1.22      8.66   -17.1      15.3 
4 4         3.04      2.30    -1.32      7.75
quinn.brmsNB |>
    emmeans(~DENSITY|SEASON, type='response') |>
    pairs()
SEASON = Spring:
 contrast   ratio lower.HPD upper.HPD
 High / Low  1.08     0.584      1.73

SEASON = Summer:
 contrast   ratio lower.HPD upper.HPD
 High / Low  2.02     1.152      3.12

SEASON = Autumn:
 contrast   ratio lower.HPD upper.HPD
 High / Low  1.05     0.514      1.72

SEASON = Winter:
 contrast   ratio lower.HPD upper.HPD
 High / Low  1.99     0.561      4.29

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
## absolute response scale
quinn.brmsNB |>
    emmeans(~DENSITY|SEASON, type='link') |>
    regrid() |>
    pairs()
SEASON = Spring:
 contrast   estimate lower.HPD upper.HPD
 High - Low    0.822    -5.549      6.44

SEASON = Summer:
 contrast   estimate lower.HPD upper.HPD
 High - Low   22.537     5.735     41.46

SEASON = Autumn:
 contrast   estimate lower.HPD upper.HPD
 High - Low    0.987   -11.540     11.97

SEASON = Winter:
 contrast   estimate lower.HPD upper.HPD
 High - Low    2.758    -0.809      6.31

Point estimate displayed: median 
HPD interval probability: 0.95 
quinn.em <- quinn.brmsNB |>
    emmeans(~DENSITY|SEASON, type='link') |>
    pairs() |>
    gather_emmeans_draws() |> 
    mutate(Fit=exp(.value))
head(quinn.em)
# A tibble: 6 × 7
# Groups:   contrast, SEASON [1]
  contrast   SEASON .chain .iteration .draw   .value   Fit
  <fct>      <fct>   <int>      <int> <int>    <dbl> <dbl>
1 High - Low Spring     NA         NA     1  0.341   1.41 
2 High - Low Spring     NA         NA     2  0.616   1.85 
3 High - Low Spring     NA         NA     3 -0.170   0.844
4 High - Low Spring     NA         NA     4  0.424   1.53 
5 High - Low Spring     NA         NA     5  0.274   1.32 
6 High - Low Spring     NA         NA     6 -0.00979 0.990
g2 <- quinn.em |>
  group_by(contrast, SEASON) |>
  median_hdci() |>
  ggplot() +
  geom_vline(xintercept=1, linetype='dashed') +
  geom_pointrange(aes(x=Fit, y=SEASON, xmin=Fit.lower, xmax=Fit.upper)) + 
  scale_x_continuous('Effect size (High/Low)', trans = scales::log2_trans(), breaks=unique(as.vector(2^(0:4 %o% c(-1,1))))) +
  theme_classic()
g2

ggplot(quinn.em, aes(x=Fit)) +
    geom_histogram() +
    geom_vline(xintercept = 1, linetype='dashed') +
    scale_x_continuous('Effect size (High/Low)', trans = scales::log2_trans(), breaks=unique(as.vector(2^(0:4 %o% c(-1,1))))) +
    facet_wrap(SEASON~contrast, scales='free')
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

quinn.em |> group_by(contrast, SEASON) |> median_hdci(Fit)
# A tibble: 4 × 8
  contrast   SEASON   Fit .lower .upper .width .point .interval
  <fct>      <fct>  <dbl>  <dbl>  <dbl>  <dbl> <chr>  <chr>    
1 High - Low Spring  1.08  0.584   1.73   0.95 median hdci     
2 High - Low Summer  2.02  1.15    3.12   0.95 median hdci     
3 High - Low Autumn  1.05  0.514   1.72   0.95 median hdci     
4 High - Low Winter  1.99  0.561   4.29   0.95 median hdci     
# Probability of effect
quinn.em |> group_by(contrast,SEASON) |> summarize(P=mean(Fit>1))
`summarise()` has grouped output by 'contrast'. You can override using the
`.groups` argument.
# A tibble: 4 × 3
# Groups:   contrast [1]
  contrast   SEASON     P
  <fct>      <fct>  <dbl>
1 High - Low Spring 0.593
2 High - Low Summer 0.997
3 High - Low Autumn 0.577
4 High - Low Winter 0.941
##Probability of effect greater than 10%
quinn.em |> group_by(contrast,SEASON) |> summarize(P=mean(Fit>1.1))
`summarise()` has grouped output by 'contrast'. You can override using the
`.groups` argument.
# A tibble: 4 × 3
# Groups:   contrast [1]
  contrast   SEASON     P
  <fct>      <fct>  <dbl>
1 High - Low Spring 0.471
2 High - Low Summer 0.991
3 High - Low Autumn 0.448
4 High - Low Winter 0.908

12 Summary figures

newdata <- quinn.rstanarmNB |>
    emmeans(~SEASON|DENSITY, type='response') |>
    as.data.frame()
Warning: Model has 0 prior weights, but we recovered 42 rows of data.
So prior weights were ignored.
head(newdata)
 SEASON DENSITY     prob lower.HPD upper.HPD
 Spring High    10.05504  5.915025  15.61156
 Summer High    48.79529 29.545096  73.58342
 Autumn High    20.08778 11.915208  30.53279
 Winter High     5.73910  2.883103   9.24907
 Spring Low     11.33008  6.349998  18.80661
 Summer Low     22.18656 13.120594  33.30095

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
g1 <- ggplot(newdata, aes(y=prob, x=SEASON, color=DENSITY)) +
    geom_pointrange(aes(ymin=lower.HPD, ymax=upper.HPD),
                    position=position_dodge(width=0.2)) + 
    theme_classic()
g1 + g2

newdata <- quinn.brmsNB %>%
    emmeans(~SEASON|DENSITY, type='response') |>
    as.data.frame()
head(newdata)
 SEASON DENSITY     prob lower.HPD upper.HPD
 Spring High    11.31608  7.644298  16.23631
 Summer High    45.31441 30.850409  62.17419
 Autumn High    19.17222 12.908595  27.43145
 Winter High     5.68584  3.294617   8.67109
 Spring Low     10.54590  6.651577  15.97995
 Summer Low     22.36061 15.374188  32.02418

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
g1 <- ggplot(newdata, aes(y=prob, x=SEASON, color=DENSITY)) +
    geom_pointrange(aes(ymin=lower.HPD, ymax=upper.HPD),
                    position=position_dodge(width=0.2)) + 
    theme_classic()
g1 + g2

13 Observation-level random effects

13.1 brms

quinn <- quinn |>
  group_by(SEASON, DENSITY) |>
  mutate(Obs = factor(1:n()))

quinn.form <- bf(RECRUITS ~ SEASON*DENSITY + (1|Obs),  family = poisson(link = 'log'))
get_prior(quinn.form,  data = quinn)
                  prior     class                    coef group resp dpar nlpar
                 (flat)         b                                              
                 (flat)         b              DENSITYLow                      
                 (flat)         b            SEASONAutumn                      
                 (flat)         b SEASONAutumn:DENSITYLow                      
                 (flat)         b            SEASONSummer                      
                 (flat)         b SEASONSummer:DENSITYLow                      
                 (flat)         b            SEASONWinter                      
                 (flat)         b SEASONWinter:DENSITYLow                      
 student_t(3, 2.6, 2.5) Intercept                                              
   student_t(3, 0, 2.5)        sd                                              
   student_t(3, 0, 2.5)        sd                           Obs                
   student_t(3, 0, 2.5)        sd               Intercept   Obs                
 lb ub       source
            default
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
       (vectorized)
            default
  0         default
  0    (vectorized)
  0    (vectorized)
quinn.brmsU <- brm(quinn.form,
                   data = quinn,
                   refresh = 0,
                   chains = 3,
                   iter = 5000,
                   thin = 5,
                   warmup = 2000)
Compiling Stan program...
Start sampling
Warning: There were 3 divergent transitions after warmup. See
https://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
to find out why this is a problem and how to eliminate them.
Warning: Examine the pairs() plot to diagnose sampling problems
preds <- posterior_predict(quinn.brmsU,  nsamples=250,  summary=FALSE)
Warning: Argument 'nsamples' is deprecated. Please use argument 'ndraws'
instead.
quinn.resids <- createDHARMa(simulatedResponse = t(preds),
                            observedResponse = quinn$RECRUITS,
                            fittedPredictedResponse = apply(preds, 2, median),
                            integerResponse = TRUE)
plot(quinn.resids)

newdata = emmeans(quinn.brmsU, ~SEASON|DENSITY, type='response') |> as.data.frame()
newdata
DENSITY = High:
 SEASON     rate lower.HPD upper.HPD
 Spring  9.83507   6.38115  13.70384
 Summer 47.12708  32.95946  61.98928
 Autumn 19.25956  12.85732  25.96017
 Winter  5.48125   3.47540   8.29847

DENSITY = Low:
 SEASON     rate lower.HPD upper.HPD
 Spring 10.81971   6.78302  15.08974
 Summer 21.62346  15.04174  29.15990
 Autumn 16.25693  11.12209  23.21730
 Winter  2.40136   0.92977   4.35164

Point estimate displayed: median 
Results are back-transformed from the log scale 
HPD interval probability: 0.95 
ggplot(newdata, aes(y=rate, x=SEASON, color=DENSITY)) +
    geom_pointrange(aes(ymin=lower.HPD, ymax=upper.HPD),
                    position=position_dodge(width=0.2))

14 References

Quinn, G. P. 1988. “Ecology of the Intertidal Pulmonate Limpet Siphonaria Diemenensis Quoy Et Gaimard. II Reproductive Patterns and Energetics.” Journalofexperimentalmarinebiologyandecology 117: 137–56.